package main
import \"fmt\"
type myType struct {
string
}
func main() {
obj := myType{\"Hello World\"}
fmt.Println(obj)
}
What is the p
No disrespect to the chosen answer, but it did not clarify the concept for me.
There are two things going on. First is anonymous fields. Second is the "promoted" field.
For anonymous fields, the field name you can use is the name of the type. The first anonymous field is "promoted", which means any field you access on the struct "passes through" to the promoted anonymous field. This shows both concepts:
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)
}
Output is:
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```
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 "Embeffffding 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}
.