Trace recursive types
Trace recursive types
A recursive type refers to itself directly or indirectly. A struct or array cannot contain itself through only struct and array components: that would require an invalid recursive representation. A pointer, slice or map can break the direct containment cycle and represent finite values.
package main
import ( "fmt")
type Node struct { Value int Next *Node}
func main() { head := &Node{Value: 2, Next: &Node{Value: 5}} sum := 0 for n := head; n != nil; n = n.Next { sum += n.Value } fmt.Println(sum)}Next stores a pointer, not an entire Node inline. nil terminates this list. The loop assumes the list has no cycle; a cycle would need explicit detection. A declaration with Next Node instead would be invalid.
Expected output:
7Represent a tree with a slice
package main
import ( "fmt")
type Tree struct { Name string Children []Tree}
func main() { t := Tree{Name: "root", Children: []Tree{{Name: "a"}, {Name: "b"}}} fmt.Println(t.Name, len(t.Children), t.Children[1].Name)}The slice descriptor can refer to an underlying array of children. The struct does not inline an infinite number of children. This example does not need pointers for each child; copying the struct can still share its child slice storage.
Expected output:
root 2 bTry it locally
Define Node with N int and Next *Node, link three nodes containing 1, 2 and 3, then count nodes until nil.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 04: Trace recursive types
Check the lesson objective before moving on.
Which field makes a recursive Node struct invalid?
What must a list traversal handle if cycles are allowed?