can a struct embed itself?

tags: learning go programming

content

  • can we do this?
type MyStruct struct {
	// some fields
	MyStruct
}
  • NO!

    • what does that even mean?
    • it’s gonna promote all its fields to its fields?
    • it’s recursive, the promotion never stops!!
      • it’s gonna infinitely expand the struct!
  • HOWEVER, it can embed its a pointer of itself:

type MyStruct struct {
	// some fields
	*MyStruct
}
  • pointers are fixed-sized, it’s not gonna infinitely expand

  • This is how linked list is built

type Node struct {
    Value int
    Next  *Node // pointer to same type
}

up

down

reference