Wednesday, February 21, 2024
HomeSoftware EngineeringFormatting Strings with Fmt in Golang

Formatting Strings with Fmt in Golang


Fmt supplies printing to straightforward output (often the console) and formatting of strings capabilities.

The fundamentals of Print and Println

The primary distinction between fmt.Print and fmt.Println is that you just solely get a newline/carriage return by default with the second. Aside from that, you can also make use of both for string formatting.

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

package deal major

import "fmt" // <--- embody fmt

func major() {
    // major
}

Instance of fmt.Print

fmt.Print("It is a Print check")

// "It is a Print check"

This can print to straightforward output with no newline on the finish.

Instance of fmt.Println

fmt.Println("It is a Println check")

// "It is a Println testn   <--- newline added
//  "

This can print to straightforward output with a newline on the finish.

Printing variables

const quantity = 37

fmt.Println("The quantity is", quantity)

// "The quantity is 37"

Discover how an area is routinely added between the strings above.

Printing advanced buildings

objects := []int {10, 20, 30, 40, 50}

size, err := fmt.Println(objects)

fmt.Println(<meta charset="utf-8">size, err)

// [10 20 30 40 50]
// 14 nil

The above prints out the listing of merchandise, adopted by the size of that string, and nil because the error.

Introducing Printf and Sprintf

These are fairly just like the Print strategies we checked out beforehand, however they provide extra flexibility for formatting.

These features make use of the formatting verbs, comparable to %v, %#v, %T and %t to call but a couple of. You may get a full listing from https://pkg.go.dev/fmt.

The best way to print decimal values

fmt.Printf("%dn", 20)
// 20

The best way to print hexadecimal values

fmt.Printf("%xn", 123.45)
// 14

The best way to print a boolean worth

fmt.Printf("%tn", 2 > 1)
// true

The best way to print floating level numbers

fmt.Printf("%fn", 123.45)
// 123.450000

The best way to print exponent numbers (scientific notation)

fmt.Printf("%en", 123.45)
// 1.234500+02

Extra superior 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 %#[]xn", 52)
52 064 0x34

Formatting by precision

Decimal precision

fmt.Printf("%.2fn", 123.4567)
// 123.46
// print with 10 areas
fmt.Printf("%10fn", 123.4567)
// 123.456700
fmt.Printf("%10.2fn", 123.4567)
// "    123.46"
fmt.Printf("%+10.2fn", 123.4567)
// "   +123.46"

Pad with 0s as a substitute of areas

fmt.Printf("%010.2fn", 123.4567)
// 0000123.46
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments