Various examples of printing and formatting in Golang


Printf method accepts a formatted string for that the codes like "%s" and "%d" in this string to indicate insertion points for values. Those values are then passed as arguments.

Example

package main

import (
	"fmt"		
)

var(
	a = 654
	b = false
	c   = 2.651
	d  = 4 + 1i
	e   = "Australia"
	f = 15.2 * 4525.321
)

func main(){	
	fmt.Printf("d for Integer: %d\n", a)
	fmt.Printf("6d for Integer: %6d\n", a)
	
	fmt.Printf("t for Boolean: %t\n", b)
	fmt.Printf("g for Float: %g\n", c)
	fmt.Printf("e for Scientific Notation: %e\n", d)
	fmt.Printf("E for Scientific Notation: %E\n", d)
	fmt.Printf("s for String: %s\n", e)
	fmt.Printf("G for Complex: %G\n", f)
	
	fmt.Printf("15s String: %15s\n", e)
	fmt.Printf("-10s String: %-10s\n",e)
	
	t:= fmt.Sprintf("Print from right: %[3]d %[2]d %[1]d\n", 11, 22, 33)
	fmt.Println(t)	
}

Output

d for Integer: 654
6d for Integer:    654
t for Boolean: false
g for Float: 2.651
e for Scientific Notation: (4.000000e+00+1.000000e+00i)
E for Scientific Notation: (4.000000E+00+1.000000E+00i)
s for String: Australia
G for Complex: 68784.8792
15s String:     Australia
-10s String: Australia
Print from right: 33 22 11
Most Helpful This Week