我正在尝试通过 casting
和使用 +
的追加将一个整数与现有字符串连接起来。但它不起作用。
package main
import (
"fmt"
)
func main() {
a := 4
b := "The value of a is "
fmt.Println(b + string(a))
}
这会在 go playground 上打印一个垃圾字符在 Unix 终端上什么也没有。这可能是什么原因?这种方法有什么问题?
最佳答案
来自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.
为了达到预期的结果,您需要使用类似 strconv.Itoa
的方法将您的 int 转换为字符串。 :
package main
import (
"fmt"
"strconv"
)
func main() {
a := 4
b := "The value of a is "
fmt.Println(b + strconv.Itoa(a))
}
关于string - 通过强制转换和使用串联运算符将整数附加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46744185/