Golang / GoLang Basics Interview Questions
What are the most important formatting verbs in Go's fmt package?
Knowing fmt format verbs lets you produce clear output for debugging, logging, and user messages. The %v verb is the universal default; specialised verbs give more control.
| Verb | Meaning | Example output |
|---|---|---|
| %v | Default format for any value | 42, true, [1 2 3] |
| %+v | Struct with field names | {Name:Alice Age:30} |
| %#v | Go-syntax representation | main.Person{Name:"Alice", Age:30} |
| %T | Type of the value | int, []string, main.Person |
| %d | Integer in decimal | 42 |
| %f / %.2f | Float / float with 2 decimal places | 3.141590 / 3.14 |
| %s | Plain string | hello |
| %q | Quoted string | "hello" |
| %x | Hex encoding | ff (int) or 68656c6c6f (string) |
| %p | Pointer address | 0xc000012080 |
| %w | Wrap an error (Errorf only) | used for error chaining |
name := "Alice" age := 30 pi := 3.14159 fmt.Printf("%s is %d years old\n", name, age) // Alice is 30 years old fmt.Printf("Pi â %.2f\n", pi) // Pi â 3.14 fmt.Printf("Type: %T\n", pi) // Type: float64 // Sprintf â format to string, no output msg := fmt.Sprintf("User: %s (age %d)", name, age) // Errorf â format and create an error err := fmt.Errorf("user %q not found (id: %d)", name, 99) // Width and padding fmt.Printf("%10s\n", "right") // right (right-align, width 10) fmt.Printf("%-10s|\n", "left") // left | (left-align, width 10) fmt.Printf("%06d\n", 42) // 000042 (zero-pad to width 6) // Printing structs type Person struct{ Name string; Age int } p := Person{"Bob", 25} fmt.Printf("%v\n", p) // {Bob 25} fmt.Printf("%+v\n", p) // {Name:Bob Age:25} fmt.Printf("%#v\n", p) // main.Person{Name:"Bob", Age:25}
More Related questions...