user10078199
user10078199

Reputation: 131

GoLang Array Index on Struct

package main

import "fmt"

type Bar struct {
    high float64
    low  float64
}

func main() {
    var bars = []Bar{}
    bars = []Bar{
        {1.0, 2.0},
        {1.1, 2.1},
        {1.2, 2.2},
        {1.3, 2.3},
        {1.4, 2.4},
        {1.5, 2.5},
    }
    fmt.Println(bars)
    testFunction(&bars)
}

func testFunction(array *[]Bar) {
    for i := 0; i < 3; i++ {
        fmt.Println(*array[i])
    }
}

https://play.golang.org/p/MZwaFALHfuy

Why can I not access the array row?

invalid operation: array[i] (type *[]Bar does not support indexing)

Upvotes: 4

Views: 8329

Answers (1)

H4xorPL
H4xorPL

Reputation: 320

Change the line in for loop to fmt.Println((*array)[i])

*array[i] would try to dereference [i]

(*array)[i] would derefence the array which is your pointer.

Working example: https://play.golang.org/p/yr6WbtS3Aq_c

Upvotes: 7

Related Questions