go - [0] 和 [ :1] in Go? 有什么区别

标签 go substring slice

我用空格分割一个字符串:

splstr = strings.Split(str, " ")

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

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

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

... : cannot convert "#" to type uint8

... : invalid operation: splstr[i][0] == "#" (mismatched types uint8 and string)

但后来我拼接了它:

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

那行得通。我明白为什么 [:1]string 类型,但为什么 [0]uint8 类型? (我正在使用 Go 1.1。)

最佳答案

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

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

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

(byte是uint8的别名)

关于go - [0] 和 [ :1] in Go? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16945816/

相关文章:

arrays - 数组切片的奇怪行为

types - golang 中的通用 slice 类型?

python - 在 tensorflow 中“分配”2D block 切片?

Golang 变量赋值

php - 如何获取两个子串之间的子串?

go - go中如何导入本地包?

string - 替换 Oracle 中字符串中特定位置的字符

c - 在c中写一个子串函数

go - 增加 ReverseProxy 的等待时间

go - 如何在 GORM 中使用动态数据结构