2

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?

Suhail Gupta
  • 19,563
  • 57
  • 170
  • 298
  • 1
    It's not printing a "garbage character"; it's printing a character with the Unicode code point 4. – Tim Cooper Oct 14 '17 at 11:48
  • Minor technical point: Note that Go doesn't do casting, only type conversion. – Flimzy Oct 14 '17 at 12:00
  • Possible duplicate of [How do int-to-string casts work in Go?](https://stackoverflow.com/questions/34808465/how-do-int-to-string-casts-work-in-go/34808496#34808496) – icza Oct 14 '17 at 12:04
  • Possible duplicate of [How do int-to-string casts work in Go?](https://stackoverflow.com/questions/34808465/how-do-int-to-string-casts-work-in-go) – Flimzy Oct 14 '17 at 12:06
  • Also see related question: [Golang: format a string without printing?](https://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265) – icza Oct 14 '17 at 12:20
  • 1
    Possible duplicate of [How to convert an int value to string in Go?](https://stackoverflow.com/questions/10105935/how-to-convert-an-int-value-to-string-in-go) – Yandry Pozo Oct 15 '17 at 00:57

2 Answers2

9

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))
}
Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
3

Use fmt.Sprintf or Printf; no casting required:

fmt.Sprintf("%s%d",s,i)
Tim Cooper
  • 144,163
  • 35
  • 302
  • 261
Kenny Grant
  • 8,222
  • 2
  • 24
  • 43