
Accessing Fields in Nested Structs in Go
Accessing Fields in Nested Structs in Go
In Go, when you have a struct that embeds another struct, you can access the fields of the inner struct through the instance of the outer struct using the dot (.
) operator. Here’s a simple example to illustrate how to access fields in a nested struct:
package main
import "fmt"
type Inner struct {
Field1 string
}
type Outer struct {
Inner Inner
}
func main() {
// Creating an instance of the Outer struct
outer := Outer{
Inner: Inner{
Field1: "Hello",
},
}
// Accessing the Field1 field of the Inner struct
fmt.Println(outer.Inner.Field1) // Output: Hello
}
In this example, the Outer
struct embeds the Inner
struct. To access the Field1
field of Inner
, you need to go through the instance of Outer
, outer
, which is done by outer.Inner.Field1
. This is the correct way to access fields in nested structs in Go.