• Documentation - https://pkg.go.dev/fmt
  • Mainly used for
    • printing to console
    • formatting strings
    • reading user input
  • Print, Println & printf
fmt.Print("Hello")  
fmt.Print("World")
// HelloWorld
 
fmt.Println("Hello")  
fmt.Println("World")
/*
Hello  
World
*/
 
fmt.Printf("Age: %d", 25)
// Age: 25
  • printf formatters

    VerbMeaning
    %vDefault value representation
    %+vStruct with field names
    %#vGo syntax representation
    %TType of value
    %dInteger
    %fFloating-point number
    %sString
    %tBoolean
    %pPointer address
  • formatted string instead of printing.

msg := fmt.Sprintf("User: %s Age: %d", "John", 25)
  • Formatted error
err := fmt.Errorf("invalid user id: %d", id)
  • Reading
    • Scan - Reads input from console.
    • Scanln - Reads input until newline.
    • Scanf - Reads formatted input.
// scan with default space delimiter
var name string  
fmt.Scan(&name)
 
// scan with \n as delimiter
fmt.Scanln(&name)
 
// scan specific type
var age int  
fmt.Scanf("%d", &age)