Go Reference ยท strings and strconv
Go strings.HasPrefix() and HasSuffix() functions
Reference for Go strings.HasPrefix, HasSuffix, CutPrefix and CutSuffix: test how a string starts or ends and remove the affix in one step, with edge cases.
strings.HasPrefix(s, prefix) reports whether s begins with prefix, and strings.HasSuffix(s, suffix) reports whether it ends with suffix. They are the simplest way to check file extensions, URL schemes, command names and protocol markers.
Go 1.20 added CutPrefix and CutSuffix, which do the test and the removal together and return a found flag.
ok := strings.HasPrefix("golang", "go") // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func HasPrefix(s, prefix string) bool func HasSuffix(s, suffix string) bool func CutPrefix(s, prefix string) (after string, found bool) func CutSuffix(s, suffix string) (before string, found bool)
| Name | Description |
|---|---|
s |
The string to examine. |
prefix, suffix |
The exact text expected at the start or end. Case-sensitive. |
Returns: HasPrefix and HasSuffix return a bool. CutPrefix returns the rest of s after the prefix and true; if the prefix is absent it returns s unchanged and false. CutSuffix is the mirror image.
Edge cases: an empty prefix or suffix always matches. If the affix is longer than s the result is false. Nothing panics, and no allocation occurs (results are substrings).
Usage notes
- Prefer
CutPrefixoverHasPrefixfollowed byTrimPrefix; it avoids repeating the literal and thelen(prefix)arithmetic that used to cause off-by-one bugs. - Case-insensitive: compare a slice of the string with
strings.EqualFold, for examplelen(s) >= 4 && strings.EqualFold(s[:4], "http")(watch for multi-byte characters), or lowercase first. - Many prefixes: loop over a slice of candidates, or use a
switchwithcase strings.HasPrefix(...). - File extensions:
strings.HasSuffix(name, ".go")works, butfilepath.Extis more robust for paths. - Not the same as
Contains.HasPrefixonly looks at the start; usestrings.Contains()for anywhere. - Performance: both are constant time apart from the comparison itself (length check plus
memequal). - Bytes:
bytes.HasPrefixandbytes.HasSuffixare the[]byteversions.