Printf Verbs Reveal Types And Shapes

Inspect values with Printf verbs: %v and %+v for fields, %#v for Go syntax, %T for the dynamic type, %q for quoted strings, and width-precision for tables.

GoCli Tooling

Code

gosnippet
27 lines
package main

import "fmt"

type Retry struct {
	Attempts int
	Backoff  float64
}

func main() {
	r := Retry{Attempts: 3, Backoff: 0.5}

	// %v 通用值;%+v 带字段名;%#v Go 语法表示
	fmt.Printf("%v\n", r)
	fmt.Printf("%+v\n", r)
	fmt.Printf("%#v\n", r)

	// %T 打印动态类型,排查接口里装了什么
	var v any = r
	fmt.Printf("type %T\n", v)

	// %q 带引号并转义;%d/%.2f 控制数值形态;%% 输出百分号本身
	fmt.Printf("msg=%q attempts=%d backoff=%.2f%%\n", "wait\tand retry", r.Attempts, r.Backoff*100)

	// 宽度+精度:右对齐的表格输出
	fmt.Printf("%8.2f\n%8.2f\n", 12.5, 133.257)
}

How the snippet works

Printf Verbs Reveal Types And Shapes is built around the function main.

Using it

The demo output is labeled (type, msg=), so the printed output reads as a trace of the operations performed.

Key statements

r := Retry{Attempts: 3, Backoff: 0.5}

Interactive Tools for This Topic

FAQ

What does Printf Verbs Reveal Types And Shapes print when run?
Run it as a complete program — the output lines carry labels such as `type`, `msg=`.