Search code examples
stringgotype-conversionint

Append int value to string


I can't seem to find a working solution: The situation is the following:

var s string
n := 1

I want to append the int value to the string s. Then increment or decrement n at some point and append the new value again

So in the end I'd have a string like this:

1213

What I tried so far:

s = s + string(rune(n)) // for some reason string(rune(n) is [] aka empty


Solution

  • You can use strconv from the strconv package

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        a := 4 
        b := 3
        c := "1"
    
        fmt.Println(c + strconv.Itoa(a) + strconv.Itoa(b))
    }
    
    

    Or you can use Sprintf from the fmt package:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        a := 4 
        b := 3
        c := "1"
        c = fmt.Sprintf("%s%d%d",c,a,b)
    
        fmt.Println(c + strconv.Itoa(a) + strconv.Itoa(b))
    }