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
How to read current directory using Readdir?
Golang HTTP GET request with parameters
Go program to find PTR pointer record of a domain
How to Convert string to float type in Go?
Avoid Unintended Variable Shadowing in Golang
How to remove multiple spaces in a string in GoLang?
Example of Interface with Type Embedding and Method Overriding in GO language
Convert Int data type to Int16 Int32 Int64
How to write backslash in Golang string?
How to convert String to Boolean Data Type Conversion in Go?