Go gotcha: Why aren't the characters concatenated?

Why doesn't these print statements give the same result?

fmt.Println("H" + "i")
fmt.Println('H' + 'i')
Hi
177
Answer

The rune literals 'H' and 'i' are integer values identifying Unicode code points: 'H' is 72 and 'i' is 105. (See What is a rune?)

You can turn a code point into a string using a conversion:

fmt.Println(string(72) + string('i')) // "Hi"

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD". The Go Programming Language Specification: Conversions

You can also use the fmt.Sprintf function:

s := fmt.Sprintf("%c%c, world!", 72, 'i')
fmt.Println(s)// "Hi, world!"

The Print with fmt cheat sheet lists the most common formatting verbs and flags.

Comments

Be the first to comment!