只是好奇想知道:为什么Go编程语言的标准库中没有像startswith、endswith等标准函数?
如果您正在使用字节,可以使用 bytes 包中的以下函数:
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}
如果直接转为字符串会比较耗费成本。如果从HTTP请求或本地文件读取数据,这个函数将非常有用。