Formatting Strings with Fmt in Golang

Fmt provides printing to standard output (usually the console) and formatting of strings capabilities.

The basics of Print and Println

The main difference between fmt.Print and fmt.Println is that you only get a newline/carriage return by default with the second one. Other than that, you can make use of either for string formatting.

Firstly, we need to import the fmt module as follows:

package main import "fmt" // <--- include fmt func main() { // main }
Code language: Go (go)

Example of fmt.Print

fmt.Print("This is a Print test") // "This is a Print test"
Code language: Go (go)

This will print to standard output without a newline at the end.

Example of fmt.Println

fmt.Println("This is a Println test") // "This is a Println test\n <--- newline added // "
Code language: Go (go)

This will print to standard output with a newline at the end.

Printing variables

const number = 37 fmt.Println("The number is", number) // "The number is 37"
Code language: Go (go)

Notice how a space is automatically added between the strings above.

Printing complex structures

items := []int {10, 20, 30, 40, 50} length, err := fmt.Println(items) fmt.Println(<meta charset="utf-8">length, err) // [10 20 30 40 50] // 14 nil
Code language: Go (go)

The above prints out the list of item, followed by the length of that string, and nil as the error.

Introducing Printf and Sprintf

These are quite similar to the Print methods we looked at previously, but they offer more flexibility for formatting.

These functions make use of the formatting verbs, such as %v, %#v, %T and %t to name yet a few. You can get a full list from https://pkg.go.dev/fmt.

How to print decimal values

fmt.Printf("%d\n", 20) // 20
Code language: Go (go)

How to print hexadecimal values

fmt.Printf("%x\n", 123.45) // 14
Code language: Go (go)

How to print a boolean value

fmt.Printf("%t\n", 2 > 1) // true
Code language: Go (go)

How to print floating point numbers

fmt.Printf("%f\n", 123.45) // 123.450000
Code language: Go (go)

How to print exponent numbers (scientific notation)

fmt.Printf("%e\n", 123.45) // 1.234500+02
Code language: Go (go)

More advanced usages

fmt.Printf("%d, %d", 10, 20) // 10 20 fmt.Printf("%[2]d %[1]d", 10, 20) // 20 10 // decimal, octal and hexadecimal fmt.Printf("%d %#[1]o %#[]x\n", 52) 52 064 0x34
Code language: Go (go)

Formatting by precision

Decimal precision

fmt.Printf("%.2f\n", 123.4567) // 123.46
Code language: Go (go)

Print with width and precision

// print with 10 spaces fmt.Printf("%10f\n", 123.4567) // 123.456700
Code language: Go (go)

Print with padding and precision

fmt.Printf("%10.2f\n", 123.4567) // " 123.46"
Code language: Go (go)

Print with + sign

fmt.Printf("%+10.2f\n", 123.4567) // " +123.46"
Code language: Go (go)

Pad with 0s instead of spaces

fmt.Printf("%010.2f\n", 123.4567) // 0000123.46
Code language: Go (go)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments