Search⌘ K

Solution Review: Anonymous Struct

Explore how to declare and use anonymous structs in Go, including how to assign values and print struct fields individually or entirely. This lesson helps you understand anonymous and named fields within structs, preparing you for working with methods next.

We'll cover the following...
Go (1.6.2)
package main
import "fmt"
type C struct { // struct
x float32
int // int type anonymous field
string // string type anonymous field
}
func main() {
c := C{3.14, 7, "hello"} // making struct via literal expression
fmt.Println(c.x, c.int, c.string) // output: 3.14 7 hello
fmt.Println(c) // output: {3.14 7 hello}
}

In the code above, look at line 4, where we declare a struct of type C. It has three fields. The first field is a named field x of type float32. The second and third ...