我正在尝试从结构中的嵌入切片访问值。我怎么能通过索引来实现,而且没有明确地调用私有嵌入对象(从包外部访问时甚至不是一个选项),如果可能的话?
package main
import (
"fmt"
)
type A struct {
aSlice
}
type aSlice []string
func main() {
a := A{[]string{"hello", "world"}}
fmt.Println(a.aSlice[0]) // works, but can't be accessed outside package
fmt.Println(a[0]) // doesn't work, but looking for this something like this
}
答案 0 :(得分:1)
我想我在这篇文章中找到了答案:golang anonymous field of type map
只有字段和方法才能被推广"当你嵌入。对于 其他一切他们只是另一个领域。
在这种情况下,结构将等同于:
type A struct {
aSlice aSlice
}
为什么只能通过A.aSlice
索引访问其值才有意义。