Go学习:字符转字符串

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)
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值