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?
value = getfield( S , field ) returns the value in the specified field of the structure S . For example, if S.a = 1 , then getfield(S,'a') returns 1 . As an alternative to getfield , use dot notation, value = S. field .
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure.
A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming.
you can not put a whole struct inside of itself because it would be infinitely recursive.
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```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With