Go结构中的无名字段? [英] Nameless fields in Go structs?
问题描述
package main
importfmt
type myType struct {
string
}
func main(){
obj:= myType {Hello World}
fmt.Println(obj)
}
结构中无名字段的用途是什么?
您可以像使用命名字段一样访问这些字段吗?
嵌入Go :您嵌入结构中的匿名字段:这通常与嵌入式结构一起使用,而不是像 string
这样的基本类型。这种类型没有推广领域来公开。
结构<$ c中匿名字段的字段或方法
f
如果xf
是一个合法选择器,表示该字段或方法<$ c $>,则称$ c> x 为提升 c> f 。
升级字段的作用类似于结构的普通字段,只是它们不能用作结构的复合字面值中的字段名。
(这里 string
本身没有字段)
请参阅嵌入何时使用指针的嵌入类型示例。
是否可以像使用命名字段一样访问这些字段?
A fmt.Println(obj.string)
会返回 Hello World
,而不是 {Hello World}
。
package main
import "fmt"
type myType struct {
string
}
func main() {
obj := myType{"Hello World"}
fmt.Println(obj)
}
What is the purpose of nameless fields in structs?
Is it possible to access these fields like you can do with named fields?
See "Embedding in Go ": you embed an anonymous field in a struct: this is generally used with an embedded struct, not a basic type like string
. That type has no "promoted field" to expose.
A field or method
f
of an anonymous field in a structx
is called promoted ifx.f
is a legal selector that denotes that field or methodf
.Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
(here string
has no field in itself)
See an example of type embedding in "Embeddding when to use pointer".
Is it possible to access these fields like you can do with named fields?
A fmt.Println(obj.string)
would return Hello World
instead of {Hello World}
.
这篇关于Go结构中的无名字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!