Search⌘ K
AI Features

Puzzle 11 Explanation: Go Log

Explore how struct embedding in Go influences the behavior of fmt.Printf when printing structs. Understand the role of the Stringer interface and how naming fields affects output. This lesson helps you identify common pitfalls and adapt code for clear, expected results.

We'll cover the following...

Try it yourself

Try executing the code below to see the result.

Go (1.16.5)
package main
import (
"fmt"
"time"
)
// Log is a log message
type Log struct {
Message string
time.Time
}
func main() {
ts := time.Date(2009, 11, 10, 0, 0, 0, 0, time.UTC)
log := Log{"Hello", ts}
fmt.Printf("%v\n", log)
}

Explanation

The %v verb will print all the struct fields.

Go (1.16.5)
package main
import (
"fmt"
)
// Point is a 2D point
type Point struct {
X int
Y int
}
func main() {
p := Point{1, 2}
fmt.Printf("%v\n", p) // {1 2}
}

We’d expect the teaser code ...