[string] How to convert an int value to string in Go?

i := 123
s := string(i) 

s is 'E', but what I want is "123"

Please tell me how can I get "123".

And in Java, I can do in this way:

String s = "ab" + "c"  // s is "abc"

how can I concat two strings in Go?

This question is related to string go int converters

The answer is


Converting int64:

n := int64(32)
str := strconv.FormatInt(n, 10)

fmt.Println(str)
// Prints "32"

ok,most of them have shown you something good. Let'me give you this:

// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
    if len(timeFormat) > 1 {
        log.SetFlags(log.Llongfile | log.LstdFlags)
        log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
    }
    var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
    switch v := tmp.(type) {
    case int:
        return strconv.Itoa(v)
    case int8:
        return strconv.FormatInt(int64(v), 10)
    case int16:
        return strconv.FormatInt(int64(v), 10)
    case int32:
        return strconv.FormatInt(int64(v), 10)
    case int64:
        return strconv.FormatInt(v, 10)
    case string:
        return v
    case float32:
        return strconv.FormatFloat(float64(v), 'f', -1, 32)
    case float64:
        return strconv.FormatFloat(v, 'f', -1, 64)
    case time.Time:
        if len(timeFormat) == 1 {
            return v.Format(timeFormat[0])
        }
        return v.Format("2006-01-02 15:04:05")
    case jsoncrack.Time:
        if len(timeFormat) == 1 {
            return v.Time().Format(timeFormat[0])
        }
        return v.Time().Format("2006-01-02 15:04:05")
    case fmt.Stringer:
        return v.String()
    case reflect.Value:
        return ToString(v.Interface(), timeFormat...)
    default:
        return ""
    }
}

fmt.Sprintf, strconv.Itoa and strconv.FormatInt will do the job. But Sprintf will use the package reflect, and it will allocate one more object, so it's not an efficient choice.

enter image description here


It is interesting to note that strconv.Itoa is shorthand for

func FormatInt(i int64, base int) string

with base 10

For Example:

strconv.Itoa(123)

is equivalent to

strconv.FormatInt(int64(123), 10)

fmt.Sprintf("%v",value);

If you know the specific type of value use the corresponding formatter for example %d for int

More info - fmt


You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

In this case both strconv and fmt.Sprintf do the same job but using the strconv package's Itoa function is the best choice, because fmt.Sprintf allocate one more object during conversion.

check the nenchmark result of both check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530

see https://play.golang.org/p/hlaz_rMa0D for example.


package main

import (
    "fmt" 
    "strconv"
)

func main(){
//First question: how to get int string?

    intValue := 123
    // keeping it in separate variable : 
    strValue := strconv.Itoa(intValue) 
    fmt.Println(strValue)

//Second question: how to concat two strings?

    firstStr := "ab"
    secondStr := "c"
    s := firstStr + secondStr
    fmt.Println(s)
}

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to go

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check Go test string contains substring Golang read request body How to uninstall Golang? Decode JSON with unknown structure Access HTTP response as string in Go How to search for an element in a golang slice How to delete an element from a Slice in Golang How to set default values in Go structs MINGW64 "make build" error: "bash: make: command not found"

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to converters

Correct way to convert size in bytes to KB, MB, GB in JavaScript How to convert an int value to string in Go? Encoding conversion in java