什么是Go语言中的[0]和[:1]的区别?

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

What is the difference between [0] and [:1] in Go?

问题

我通过空格分割了一个字符串:

splstr = strings.Split(str, " ")

然后我遍历每个单词,并查看第一个字符,像这样:

splstr[i][0] == "#"

但是我从那一行得到了这些错误:

> ...:无法将“#”转换为uint8类型
>
> ...:无效操作:splstr[i][0] == "#"(类型不匹配:uint8和string)

但是后来我进行了拼接:

splstr[i][:1] == "#"

这样就可以了。我明白为什么[:1]string类型,但为什么[0]uint8类型?(我使用的是Go 1.1版本。)

英文:

I split a string by spaces:

splstr = strings.Split(str, " ")

Then I iterate each word, and look at the first character like this:

splstr[i][0] == "#"

But I got these errors from that line:

> ... : cannot convert "#" to type uint8
>
> ... : invalid operation: splstr[i][0] == "#" (mismatched types uint8 and string)

But then I spliced it:

splstr[i][:1] == "#"

And that works. I get why [:1] is of type string, but why is [0] of type uint8? (I'm using Go 1.1.)

答案1

得分: 10

因为字符串上的数组表示法可以访问字符串的字节,如语言规范所述:

http://golang.org/ref/spec#String_types

字符串的字节可以通过整数索引0到len(s)-1来访问。

(byte是uint8的别名)

英文:

Because the array notation on a string gives access to the string's bytes, as documented in the language spec:

http://golang.org/ref/spec#String_types

> A string's bytes can be accessed by integer indices 0 through len(s)-1.

(byte is an alias for uint8)

答案2

得分: 4

[x:x] ([:x][0:x] 的一种形式) 将会在一个切片中切出另一个切片,而 [x] 将会检索索引为 x 的对象。下面是它们的区别:

arr := "#####"
fmt.Println(arr[:1]) // 将会打印出一个字符串
fmt.Println(arr[0]) // 将会打印出一个字节

如果将 string 转换为 []byte

arr := []byte("#####")
fmt.Println(arr[:1]) // 将会打印出一个字节切片
fmt.Println(arr[0]) // 将会打印出一个字节

你可以在 http://play.golang.org/p/OOZQqXTaYK 上自己尝试一下。

英文:

[x:x] ([:x] is a form of [0:x]) will cut a slice into another slice while [x] will retrieve the object at index x. The difference is shown below:

arr := "#####"
fmt.Println(arr[:1]) // will print out a string
fmt.Println(arr[0]) // will print out a byte

If the string is converted into []byte:

arr := []byte("#####")
fmt.Println(arr[:1]) // will print out a slice of bytes
fmt.Println(arr[0]) // will print out a byte

You can try this yourself at http://play.golang.org/p/OOZQqXTaYK

huangapple
  • 本文由 发表于 2013年6月6日 01:03:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/16945816.html
匿名

发表评论

匿名网友

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

确定