4

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?

6
  • 1
    It's not printing a "garbage character"; it's printing a character with the Unicode code point 4. Commented Oct 14, 2017 at 11:48
  • Minor technical point: Note that Go doesn't do casting, only type conversion. Commented Oct 14, 2017 at 12:00
  • Possible duplicate of How do int-to-string casts work in Go? Commented Oct 14, 2017 at 12:04
  • Possible duplicate of How do int-to-string casts work in Go? Commented Oct 14, 2017 at 12:06
  • 1
    Possible duplicate of How to convert an int value to string in Go? Commented Oct 15, 2017 at 0:57

2 Answers 2

12

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))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why is it like that?
That's how the language is defined.
7

Use fmt.Sprintf or Printf; no casting required:

fmt.Sprintf("%s%d",s,i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.