从结构中的嵌入式切片访问值
Accessing values from embedded slice in struct
我正在尝试从结构中的嵌入式切片访问值。如果可能的话,我如何通过索引来做到这一点,而不是显式调用私有嵌入对象(从包外部访问时甚至不是一个选项)?
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
}
我想我在这个post中找到了答案:golang anonymous field of type map
Only fields and methods may be "promoted" when you embed. For
everything else they act as just another field.
在这种情况下,结构相当于:
type A struct {
aSlice aSlice
}
这就是为什么它的值只能通过 A.aSlice
索引访问的原因。
如果将切片声明为导出类型,则可以访问嵌入切片。但是你还是不能做索引。
package a
type Slice []string
type A struct {
Slice
}
package main
import "a"
func main() {
_a := a.AB{[]string{"hello", "world"}}
fmt.Println(_a.Slice[0])
}
我正在尝试从结构中的嵌入式切片访问值。如果可能的话,我如何通过索引来做到这一点,而不是显式调用私有嵌入对象(从包外部访问时甚至不是一个选项)?
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
}
我想我在这个post中找到了答案:golang anonymous field of type map
Only fields and methods may be "promoted" when you embed. For everything else they act as just another field.
在这种情况下,结构相当于:
type A struct {
aSlice aSlice
}
这就是为什么它的值只能通过 A.aSlice
索引访问的原因。
如果将切片声明为导出类型,则可以访问嵌入切片。但是你还是不能做索引。
package a
type Slice []string
type A struct {
Slice
}
package main
import "a"
func main() {
_a := a.AB{[]string{"hello", "world"}}
fmt.Println(_a.Slice[0])
}