Golang in sixty seconds — string formatting

Spool of string
Photo by Mae Mu on Unsplash

If you've done your first go tutorial, it probably went something like this:

fmt.Println("Hello World!") // Hello World!

However if you try to use Println on something more complex than a string, you may get surprising results.

type person struct {
 name string
 age  int
}
fmt.Println(person{name: "Alice", age: 30}) //{Alice 30}

In this example, if you want to print out the keys as well as the values you will need to use a format string.

fmt.Printf("person = %+v", person{name: "Alice", age: 30}) 
    // person = {name:Alice age:30}

%v will print the value in a default format. When printing structs, the plus flag (%+v) adds field names. There are a large number of verbs documented in the official docs.

How to format a string without printing it? You can usefmt.Sprintf instead the same way you would use fmt.Printf.

Richard Bell

Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.