Golang没有专门的字符类型,用int32来存储UTF-8字符,int32有一个别名叫做rune,用单引号声明的字符默认类型为rune。
在需要字符串的地方,rune不能直接使用而是要先用转成字符串,不像JAVA里“abc” + 'd'这样的可以自动转。
转换方式:
单个rune
str := string('/')
或者rune数组转成字符串
str := string([]rune{os.PathSeparator,'a','b','c'})
rune常见报错如下所示:
1 package main
2
3 import (
4 fmt
5 os
6 strings
7 )
8
9 func main() {
10 var str string
11 str = '/' //int32或者叫rune
12 str = "str:" + os.PathSeparator //int32或者叫rune
13 fmt.Printf("%v\n", str)
14
15 var rootdir = "/data/web_log"
16 if !strings.HasSuffix(rootdir, os.PathSeparator) {
17 rootdir = rootdir + os.PathSeparator
18 }
19 fmt.Printf("%v\n", rootdir)
20 }
# 编译上述代码可得到如下错误:
./runego.go:11:6: cannot use '/' (type rune) as type string in assignment
./runego.go:12:15: cannot convert "str:" (type untyped string) to type rune
./runego.go:12:15: invalid operation: "str:" + os.PathSeparator (mismatched types string and rune)
./runego.go:16:23: cannot use os.PathSeparator (type rune) as type string in argument to strings.HasSuffix
./runego.go:17:21: cannot convert os.PathSeparator (type untyped number) to type string
./runego.go:17:21: invalid operation: rootdir + os.PathSeparator (mismatched types string and rune)