Notessh2a

String Formatting

  • General:

    PlaceholderDescriptionUsageOutput
    %vDefault variable format.("%v", 123)123
    %+vStruct format with field names.("%+v", Person{Name: "John", Age: 35}){Name:John Age:35}
    %#vGo syntax representation of the value.("%#v", []int{1, 2, 3})[]int{1, 2, 3}
    %TType of the value.("%T", 123)int
    %pHexadecimal memory address.("%p", &x)0xc000098040
    %%Literal % sign.("%%")%
  • Boolean:

    PlaceholderDescriptionUsageOutput
    %tBoolean value.("%t", true)true
  • Integer:

    PlaceholderDescriptionUsageOutput
    %dInteger in base 10.("%d", 123), ("%d", 'A')123, 65
    %bInteger in base 2.("%b", 123)1111011
    %oInteger in base 8.("%o", 123)173
    %xInteger in base 16 with lowercase letters.("%x", 123)7b
    %XInteger in base 16 with uppercase letters.("%X", 123) , ("%X", 'é')7B, E9
    %cUnicode code point character.("%c", 65), ("%c", 'A')A, A
    %UUnicode code point.("%U", 65), ("%U", 'é')U+0041, U+00E9
  • Floats:

    PlaceholderDescriptionUsageOutput
    %fDecimal format for floating-point numbers.("%f", 123.456)123.456000
    %eScientific notation with lowercase e.("%e", 123.456)1.234560e+02
    %EScientific notation with uppercase E.("%E", 123.456)1.234560E+02
  • String (slice of bytes):

    PlaceholderDescriptionUsageOutput
    %sString (uninterpreted) without quotes.("%s", "hello \n")hello \n
    %qDouble-quoted string.("%q", "hello")"hello"

Examples:

  1. name := "John"
    age := 35
    char := 97
    fmt.Printf("Name: %s, Age: %d, Char: %c ", name, age, char) // Name: John, Age: 35, Char: a
  2. pi := 3.14159
    fmt.Printf("Pi: %.2f", pi) // Pi: 3.14
  3. You can also use [n] to explicitly reference the nth argument in fmt, which lets you reuse (optimize) the same already-evaluated value multiple times.

    func expensiveFunc(a int) int {
    	fmt.Println("Calculated")
    	return a
    }
    • Unoptimized:

      func main() {
      	fmt.Printf("%v and %v", expensiveFunc(5), expensiveFunc(5))
      }
      
      // Calculated
      // Calculated
      // 5 and 5
    • Optimized:

      func main() {
      	fmt.Printf("%[1]v and %[1]v", expensiveFunc(5))
      }
      
      // Calculated
      // 5 and 5