go学习笔记之常量注意点

常量之字符串

在Go中字符串是不可变的,例如下面的代码编译时会报错:cannot assign to s[0]

var s string = “hello”
s[0] = ‘c’

但如果真的想要修改怎么办呢?下面的代码可以实现:

s := “hello”
c := []byte(s) // 将字符串 s 转换为 []byte 类型
c[0] = ‘c’
s2 := string(c) // 再转换回 string 类型
fmt.Printf(“%s\n”, s2)

常量之输出多行字符串

如果要声明一个多行的字符串怎么办?可以通过` 来声明:

m := hello
world

` 括起的字符串为Raw字符串,即字符串在代码中的形式就是打印时的形式,它没有字符转义,换行也将原样输出。例如本例中会输出:

hello
world

猜你喜欢

转载自blog.csdn.net/zf766045962/article/details/79605211
今日推荐