Trace dynamic type and value
Trace dynamic type and value
An interface value conceptually contains a dynamic concrete type and a dynamic value, or neither when nil. The declared interface type determines which methods can be called; the dynamic type determines the implementation invoked. This is a semantic model, not a promised physical memory layout.
package main
import ( "fmt")
type Labeler interface{ Label() string }type A int
func (A) Label() string { return "A" }
type B int
func (B) Label() string { return "B" }func main() { var x Labeler = A(1) fmt.Printf("%T %s\n", x, x.Label()) x = B(2) fmt.Printf("%T %s\n", x, x.Label())}The static type Labeler stays the same while method dispatch selects A or B. Assigning an interface value to another compatible interface preserves the underlying dynamic concrete type and value; it does not nest a second interface value inside the first.
Expected output:
main.A Amain.B BObserve copying and sharing
package main
import ( "fmt")
type Item struct{ N int }
func main() { a := Item{N: 1} var x any = a var y any = &a a.N = 8 fmt.Println(x) fmt.Println(y.(*Item).N)}Assigning the struct to x copies its value. Assigning its address to y copies a pointer to a, so later field changes are visible through it. The expression y.(*Item) is a type assertion: it obtains the concrete pointer when the type matches. The next assertion lesson teaches safe checks. A struct containing references can still share nested data.
Expected output:
{1}8Try it locally
Assign a defined type Score with underlying int to any, then copy that interface into another any variable. Print its dynamic type and value for Score(9).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 05: Trace dynamic type and value
Check the lesson objective before moving on.
What determines the implementation called through an interface?
What happens when a struct value with only int fields is assigned to any?