当切片是指针时,通过索引访问切片。

huangapple go评论79阅读模式
英文:

Accessing slice by index when slice is pointer

问题

在这种情况下,是否有一种简便的方法来访问x.Bar[0]

直接尝试会因为明显的原因而导致(type *[]string does not support indexing)的错误。

type A struct {
    B *[]string
}

x := &A{B: &[]string{"1", "2"}}

对于上述情况,可以使用以下简写方式访问x.Bar[0]

x.B[0]
英文:

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"}}

答案1

得分: 8

这是要翻译的内容:

它将是

    (*x.Bar)[0]

你可以使用括号来改变运算符的优先级:`[]`的优先级高于`*`。
英文:

It would be

(*x.Bar)[0]

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

huangapple
  • 本文由 发表于 2017年7月20日 04:06:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/45200078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定