How to Use strings.HasPrefix in Go: Simple Guide
In Go, use
strings.HasPrefix to check if a string starts with a specific prefix. It returns true if the string begins with the prefix, otherwise false. Import the strings package to use this function.Syntax
The strings.HasPrefix function takes two arguments: the full string and the prefix string. It returns a boolean value indicating if the full string starts with the prefix.
- strings.HasPrefix(s, prefix string) bool
s: The string to check.prefix: The prefix to look for at the start ofs.- Returns
trueifsstarts withprefix, otherwisefalse.
go
package main import ( "fmt" "strings" ) func main() { s := "golang programming" prefix := "go" result := strings.HasPrefix(s, prefix) fmt.Println(result) // true }
Output
true
Example
This example shows how to use strings.HasPrefix to check different prefixes in a string and print the results.
go
package main import ( "fmt" "strings" ) func main() { text := "hello world" fmt.Println(strings.HasPrefix(text, "he")) // true fmt.Println(strings.HasPrefix(text, "hello")) // true fmt.Println(strings.HasPrefix(text, "world")) // false fmt.Println(strings.HasPrefix(text, "")) // true (empty prefix always matches) }
Output
true
true
false
true
Common Pitfalls
Some common mistakes when using strings.HasPrefix include:
- Forgetting to import the
stringspackage. - Confusing
HasPrefixwith case-insensitive checks (it is case-sensitive). - Expecting it to check anywhere in the string instead of only at the start.
- Using
nilor empty strings incorrectly.
Always remember strings.HasPrefix is case-sensitive and only checks the start of the string.
go
package main import ( "fmt" "strings" ) func main() { text := "GoLang" // Wrong: case-insensitive check (this returns false) fmt.Println(strings.HasPrefix(text, "go")) // Right: exact case match fmt.Println(strings.HasPrefix(text, "Go")) }
Output
false
true
Quick Reference
| Function | Description | Returns |
|---|---|---|
| strings.HasPrefix(s, prefix string) | Checks if string s starts with prefix | bool (true or false) |
| Case sensitivity | The check is case-sensitive | N/A |
| Empty prefix | Always returns true if prefix is empty | true |
| Import | Requires importing the strings package | N/A |
Key Takeaways
Use strings.HasPrefix to check if a string starts with a specific prefix in Go.
Remember that HasPrefix is case-sensitive and only checks the start of the string.
Always import the strings package before using HasPrefix.
An empty prefix always returns true when checked with HasPrefix.
Use exact case matches to get correct results with HasPrefix.