转换 []int 到 rune

huangapple go评论68阅读模式
英文:

Go []int to rune

问题

for pos, char := range s {
    	fmt.Println( utf8.RuneLen(char) )
}

这段代码在Go(v1之前)中可以工作,但在Go1中无法工作。

> 无法将char(类型为[]int)作为函数参数的类型rune使用

我运行了go fix命令,将“utf8”导入更新为“unicode/utf8”,但现在我得到了之前的错误。

rune的文档提到一个简单的转换将解决这个错误。

英文:
for pos, char := range s {
    	fmt.Println( utf8.RuneLen(char) )
}

This code works in Go (pre v1) but doesn't work in Go1.

> cannot use char (type []int) as type rune in function argument

I ran go fix which updated the "utf8" import to "unicode/utf8", but now I get the previous err.

The docs for rune mention a trivial conversion will resolve this error.

答案1

得分: 4

你发布的代码在Go1中有效。假设s是一个字符串。

确保你没有意外地引入或使用名为char的其他类型为[]int的变量,并确保你的代码中没有拼写错误,这可能导致意外使用不同的变量。

英文:

The code you posted works in Go1. Assuming s is a string.

Make sure you aren't unexpectedly introducing or using some other variable named char which has type []int, and make sure there are no typos in your code which would lead to unexpected usage of a different variable.

huangapple
  • 本文由 发表于 2012年4月13日 23:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/10144139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定