Ultimate Golang String Formatting Cheat Sheet

Arindam Roy
The Startup
Published in
3 min readAug 28, 2019

--

Photo by Jason Leung on Unsplash

As a Golang developer, often times we need to be able to format strings the right way. Given the number of options Golang provides and the various scenarios that occur while formatting string, it’s impossible to have all the string formatting syntaxes and capabilities memorized to your memory. So, I decided to create this cheat sheet, which basically contains almost every string formatting use case you will ever need.

Object Formatting

Sample struct that we will use:

type Student struct {
Id int64
Name string
Grade int
CurrentScore float32
}

Let’s create and instance of this:

student := Student{
Id: 50,
Name: "John Smith",
Grade: 5,
CurrentScore: 3.8,
}

Print the Struct

Syntax:

result := fmt.Sprintf("%v", student)

Output:

{50 John Smith 5 3.8}

Print the Struct With Field Names

Syntax:

result := fmt.Sprintf("%+v", student)

Output:

{Id:50 Name:John Smith Grade:5 CurrentScore:3.8}

--

--

Arindam Roy
The Startup

Product @hyperverge. I write about a lot of things, mostly tech.