Go string formatting

String formatting in Go

How to properly format strings in Golang and print them


String Formatting is the process of dynamically building strings based on variables and preset values. For example, lets say you are bulding a client dashboard that displays a welcome message. For this you might want to create a greeting that is along the lines of:

Hello <name> The weather today is <current_temperature> degrees. You have <email_count> new emails..

To do this you could do:

    name := "John Smith" // A dummy name
emailCount := 3 // A representation of users # of new emails
currentTemperature := 20.3567 // A representation of the current temperature in celsius
fmt.Printf("Hello, %s The weather today is %f degrees. You have %d new emails.",
    name, currentTemperature, emailCount)

Note that fmt.Printf() can be used to format and immediately print strings. You can also use fmt.Sprintf() to just build the string and use it later.

For example:

    name := "John Smith" // A dummy name
emailCount := 3 // A representation of users # of new emails
currentTemperature := 20.3567 // A representation of the current temperature in celsius
// Create greeting string to be used later
greeting := fmt.Sprintf("Hello, %s The weather today is %b degrees. You have %d new emails.",
    name, currentTemperature, emailCount)

Here's an extra example

    package main

import "fmt" // More info about % operators can be found here: https://golang.org/pkg/fmt/
// Coin is a struct to represent coins
type Coin struct {
    value int    // How much the coin is worth in cents as an int
    name  string // The colloquial name of the coin
}

// A function showing off print formatting with
func main() {
    // Example of formatting with ints
    number := 3
    fmt.Printf("Value of number: %d", number)
    // Example of formatting with floats
    pi := 3.14159
    fmt.Printf("\nValue of pi: %f", pi)
    // Example of formatting with strings
    greeting := "Hello World!"
    fmt.Printf("\nValue of greeting: %s", greeting)
    // Example of formatting with struct instances
    quarter := Coin{value: 25, name: "Quarter"} // Printing a struct instance prints it's values
    fmt.Printf("\nValues of a quarter: %v\nValues of a quarter with field names: %+v",
        quarter, quarter)
    // Example of printing what variables types are
    fmt.Printf("\nThe types of number, greeting and quater are %T, %T, and %T",
        number, greeting, quarter)
}