Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing slice by index when slice is pointer [duplicate]

Tags:

go

Is there a short hand for accessing x.Bar[0] in the following case?

The direct attempt results in (type *[]string does not support indexing) for obvious reasons

type A struct {
    B *[]string
}


x := &Foo{Bar: &[]string{"1", "2"}}
like image 584
salient Avatar asked Dec 12 '25 05:12

salient


1 Answers

It would be

(*x.Bar)[0]

You use parentheses to change the precedence of operators: [] has a higher precedence than *.

like image 109
zerkms Avatar answered Dec 15 '25 20:12

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!