DEV Community

indiewebdev
indiewebdev

Posted on

Golang Notes - 4

fmt package formatted output

%d %f

fmt.Printf("%d - %f\n", 7, 19.1) // %d decimal %f float

fmt.Printf("%.3f\n", 19.2322424) // 3 point

fmt.Printf("%+d\n", 7) // print sign of decimal
Enter fullscreen mode Exit fullscreen mode

%s

fmt.Printf("%s\n", "your string")
Enter fullscreen mode Exit fullscreen mode

%q

fmt.Printf("%q\n", "your quoted string")
Enter fullscreen mode Exit fullscreen mode

%v

type Student struct {
    Age int
}

fmt.Printf("%v %v %v\n", "print any type", 1, 1.9)
/*
%v  the value in a default format
%+v  adds field names
%#v a Go-syntax representation of the value
*/
age := &Student{Age:4}
fmt.Printf("%v %+v %#v\n", age, age, age)
// &{4} &{Age:4} &main.Student{Age:4}
Enter fullscreen mode Exit fullscreen mode

%T

fmt.Printf("%T\n", "print type of")
Enter fullscreen mode Exit fullscreen mode

%t

fmt.Printf("%t\n", false)  // print bool type
Enter fullscreen mode Exit fullscreen mode

%b

fmt.Printf("%b\n", 10)  // print as base 2

fmt.Printf("%08b\n", 10)  // 8 bit format with leading zeros
Enter fullscreen mode Exit fullscreen mode

%x

fmt.Printf("%x\n", 10)  //  base 16 hexadecimal
Enter fullscreen mode Exit fullscreen mode

Top comments (0)