我很好奇: 为什么在 Go 编程语言中没有像 startswith、 endswith 这样的标准函数作为标准库的一部分呢?
绳子包包含 HasPrefix和 哈苏菲克斯。
import "strings" startsWith := strings.HasPrefix("prefix", "pre") // true endsWith := strings.HasSuffix("suffix", "fix") // true
Play.golang.org
如果使用的是字节,则可以从字节中使用这些函数 包装:
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(""))) }
它比先转换成字符串的成本要低。如果您正在阅读,它很有用 或从本地文件读取。