I am trying to concatenate an integer with an existing string by casting
and the appending using +
. But it doesn't work.
package main
import (
"fmt"
)
func main() {
a := 4
b := "The value of a is "
fmt.Println(b + string(a))
}
This prints a garbage character on go playground and nothing on the Unix terminal. What could be the reason for this? What is incorrect with this method?
From the Go language spec:
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.
In order to achieve the desired result, you need to convert your int to a string using a method like strconv.Itoa
:
package main
import (
"fmt"
"strconv"
)
func main() {
a := 4
b := "The value of a is "
fmt.Println(b + strconv.Itoa(a))
}
Use fmt.Sprintf
or Printf
; no casting required:
fmt.Sprintf("%s%d",s,i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With