No startswith,endswith functions in Go?

后端 未结 2 847
攒了一身酷
攒了一身酷 2021-01-30 04:35

Just curious to findout: why aren\'t there standard functions like startswith, endswith, etc as part of the standard libraries in the Go programming language?

2条回答
  •  庸人自扰
    2021-01-30 05:10

    If you are working with bytes, you can use these functions from the bytes package:

    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("")))
    }
    

    It will be less costly than converting to string first. Useful if you are reading in from an HTTP request, or reading from a local file.

    • https://golang.org/pkg/bytes#HasPrefix
    • https://golang.org/pkg/bytes#HasSuffix

提交回复
热议问题