No startswith,endswith functions in Go?
Asked Answered
Y

2

186

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?

Yokefellow answered 6/11, 2012 at 3:45 Comment(0)
T
322

The strings package contains HasPrefix and HasSuffix.

import "strings"

startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true

play.golang.org

Turney answered 6/11, 2012 at 3:49 Comment(0)
F
4

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.

Freund answered 17/12, 2020 at 21:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.