package main
import "fmt"
type myType struct {
string
}
func main() {
obj := myType{"Hello World"}
fmt.Println(obj)
}
Run Code Online (Sandbox Code Playgroud)
结构中无名字段的目的是什么?
是否可以像使用命名字段一样访问这些字段?
dav*_*000 68
没有不尊重所选答案,但它并没有为我澄清这个概念。
有两件事正在发生。首先是匿名字段。二是“晋升”领域。
对于匿名字段,您可以使用的字段名称是类型的名称。第一个匿名字段是“提升的”,这意味着您在结构上访问的任何字段“都会传递”到提升的匿名字段。这显示了两个概念:
package main
import (
"fmt"
"time"
)
type Widget struct {
name string
}
type WrappedWidget struct {
Widget // this is the promoted field
time.Time // this is another anonymous field that has a runtime name of Time
price int64 // normal field
}
func main() {
widget := Widget{"my widget"}
wrappedWidget := WrappedWidget{widget, time.Now(), 1234}
fmt.Printf("Widget named %s, created at %s, has price %d\n",
wrappedWidget.name, // name is passed on to the wrapped Widget since it's
// the promoted field
wrappedWidget.Time, // We access the anonymous time.Time as Time
wrappedWidget.price)
fmt.Printf("Widget named %s, created at %s, has price %d\n",
wrappedWidget.Widget.name, // We can also access the Widget directly
// via Widget
wrappedWidget.Time,
wrappedWidget.price)
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234
Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234```
Run Code Online (Sandbox Code Playgroud)