GoGoPrimer
< Back to module

Basic syntax

Strings and formatting

A `string` in Go is an immutable sequence of UTF-8-encoded bytes: you cannot modify a character in place, you always build a new string. Concatenation is done with `+`.

firstName := "Ada"
lastName := "Lovelace"
fullName := firstName + " " + lastName
fmt.Println(fullName) // Ada Lovelace

`fmt.Println` prints values separated by spaces followed by a newline. `fmt.Printf` (formatted) and `fmt.Sprintf` (returns a string instead of printing) use verbs starting with `%` to precisely control the output.

name := "Ada"
age := 36
fmt.Printf("%s a %d ans\n", name, age)
// Ada a 36 ans
 
message := fmt.Sprintf("%s a %d ans", name, age)
// message contient la chaîne, sans l'afficher

The most-used verbs: `%s` for a string, `%d` for an integer, `%f` for a floating-point number (`%.2f` for two decimals), `%t` for a boolean, and `%v` which prints any value with its default representation. This last one is very handy for exploring a data structure during development.

`go vet`, the static analyzer shipped with Go, catches mismatches between the verbs used in `Printf` and the arguments provided (for example `%d` on a string). It's a common mistake worth letting the tooling catch for you.

Your turn

With `city := "Paris"` and `temperature := 18.4`, use `fmt.Printf` to print: `Paris: 18.4°C` with a single decimal place.

package main
 
import "fmt"
 
func main() {
city := "Paris"
temperature := 18.4
// ton Printf ici
}