目录

前言

正文

前言

其他编程语言总会涉及到字符串和其他数据类型的转换,在Golang中也不例外。今天我们就来看看Golang在开发过程中是如何进行数字与字符串之间的转换的。

正文

首先,在node.js中,我们知道其他变量和字符用“+”加号拼接时都会自动转成字符串,比如

var str = "hello"+100 // 字符串与数字100拼接,结果str会转换成字符串
console.log(str)
复制代码

输出结果:hello100。

那么,如果是Golang的话,会发生什么呢?

str := "hello" + 100
复制代码

是的,发生了报错,报错信息如下:

# command-line-arguments ./main.go:6:17: cannot convert "hello" (type untyped string) to type int ./main.go:6:17: invalid operation: "hello" + 100 (mismatched types string and int)

大致的意思是说,不能将字符串'hello'转换成int类型,二者在进行加号运算时,类型是不匹配的。这一点其实和C++很像,加号在字符串中表示字符串的连接,在整型变量中表示数据的计算。

数字转换成字符串

如果我们想实现二者的拼接,该怎么做呢?

我们可以使用一个工具包strconv,其中,有个方法是Itoa(),具体怎么使用呢?

请看代码示例:

package main

import "fmt"
import "strconv"

func main() {
	//str := "hello" + 100 // 取消注释会报错
	str := strconv.Itoa(100)
	str = "hello" + str
	fmt.Println(str)
}
复制代码

代码输出结果:

hello100

字符串转换成数字

如果我们想把字符串转换成数字,应该怎么操作呢?

有没有类似方便的方法呢?是的,它就是Atoi()。

具体如何使用呢,也非常简单,请看代码:

package main

import "fmt"
import "strconv"

func main() {
	//num := "123" + 100 // 取消注释会报错
	num,_ := strconv.Atoi("123")
	res := num + 100
	fmt.Println(res)
}
复制代码

代码输出结果:

223

上面的代码逻辑也非常简单,就是将字符串“123”转换成数字123,再与100进行求和运算,得到结果223。