Use struct pointers and promoted fields
Use struct pointers and promoted fields
When p points to a struct, p.Field is shorthand for (*p).Field. This lets a function mutate a caller’s struct through a pointer. Embedded fields can also promote selectors through pointer values. A selector must resolve unambiguously to a field; a nil pointer must not be dereferenced.
package main
import ( "fmt")
type Stock struct{ Count int }
func add(p *Stock, n int) { p.Count += n }func main() { s := Stock{Count: 3} add(&s, 4) fmt.Println(s.Count) p := &s fmt.Println((*p).Count, p.Count)}Both selector forms read the same field. add expects a non-nil pointer. The pointer parameter itself is copied, but the field mutation affects s.
Expected output:
77 7Handle embedded pointers and ambiguity
package main
import ( "fmt")
type Left struct{ Value int }type Right struct{ Value int }type Both struct { Left Right}type Optional struct{ *Left }
func main() { b := Both{Left: Left{Value: 2}, Right: Right{Value: 5}} fmt.Println(b.Left.Value, b.Right.Value) var o Optional fmt.Println(o.Left == nil) o.Left = &Left{Value: 8} fmt.Println(o.Value)}b.Value would be ambiguous because both embedded fields provide Value at the same depth. Select the path explicitly. The zero value of Optional embeds a nil *Left, so reading o.Value before initialization would panic. Check o.Left first.
Expected output:
2 5true8Try it locally
Define Counter with N int and Session embedding *Counter. Initialize the embedded pointer to Counter{N:4}, increase the promoted N through a *Session by 2, and print the underlying Counter.N.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 06: Use struct pointers and promoted fields
Check the lesson objective before moving on.
What does p.Count mean for a non-nil *Stock?
Two embedded fields expose Value at the same depth. How do you access one?