CodeBlanks Logo Icon CodeBlanks

Format verbs

Learn common verbs like %v, %d and %s.

Verbs

The most common verbs:

%v   default format         {Ada 36}
%+v  with field names       {Ad:Ada Yas:36}
%#v  Go syntax              main.Kisi{Ad:"Ada", Yas:36}
%T   type                   main.Kisi
%d   integer   %x hex        %b binary
%s   string    %q quoted string
%f   decimal   %e scientific
%t   bool      %p pointer
%%   a percent sign

When debugging, %+v and %#v show a value's contents most clearly.

The Stringer interface

If a type has a String() string method, %v and %s use it:

type Renk int

func (r Renk) String() string {
    return [...]string{"kırmızı", "yeşil", "mavi"}[r]
}

fmt.Println(Renk(1))  // yeşil

Error() string plays the same role for errors. Careful: calling fmt.Sprintf("%v", r) inside String causes infinite recursion.

Practice Write a Stringer

For type Durum int, define the constants Aktif (0) and Pasif (1) with iota. The String() method returns "aktif"/"pasif". Print fmt.Printf("%v %d\n", Pasif, Pasif).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Durum int

const (
    Aktif Durum = iota
    Pasif
)

func (d Durum) String() string {
    if d == Aktif {
        return "aktif"
    }
    return "pasif"
}

func main() {
    fmt.Printf("%v %d\n", Pasif, Pasif)
}

Expected output

pasif 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>fmt.Printf("%q", "a\tb")</code> print?

  • a\tb
  • %q
  • "a\tb" (escaped and quoted) Correct answer
  • a b

Explanation: %q writes the value in Go string syntax, escaping special characters; ideal for spotting invisible characters.

2 Print the type

Question
fmt.Printf("____
", 3.5)  // float64
Answer
fmt.Printf("%T
", 3.5)  // float64

Explanation: %T prints the value's Go type.

3 Verb and output

Term Meaning
%v {Ada 36}
%+v {Ad:Ada Yas:36}
%T main.Kisi
%x (255) ff

All lessons in Intermediate