Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending integer to a string by casting and using the concatenation operator

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?

like image 852
Suhail Gupta Avatar asked Dec 06 '22 13:12

Suhail Gupta


2 Answers

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))
}
like image 69
Tim Cooper Avatar answered Feb 15 '23 07:02

Tim Cooper


Use fmt.Sprintf or Printf; no casting required:

fmt.Sprintf("%s%d",s,i)
like image 28
Kenny Grant Avatar answered Feb 15 '23 06:02

Kenny Grant