How to Use strings.HasSuffix in Go: Syntax and Examples
In Go, use
strings.HasSuffix(s, suffix) to check if the string s ends with the substring suffix. It returns true if s ends with suffix, otherwise false. Remember to import the strings package before using it.Syntax
The function strings.HasSuffix has this syntax:
strings.HasSuffix(s string, suffix string) bool
Here, s is the main string you want to check, and suffix is the ending substring you want to find. The function returns true if s ends with suffix, otherwise false.
go
package main import ( "fmt" "strings" ) func main() { s := "hello.go" suffix := ".go" result := strings.HasSuffix(s, suffix) fmt.Println(result) // true }
Output
true
Example
This example shows how to use strings.HasSuffix to check different strings for a suffix. It prints true or false depending on whether the string ends with the given suffix.
go
package main import ( "fmt" "strings" ) func main() { files := []string{"report.pdf", "image.png", "notes.txt", "archive.zip"} suffix := ".txt" for _, file := range files { if strings.HasSuffix(file, suffix) { fmt.Printf("%s ends with %s\n", file, suffix) } else { fmt.Printf("%s does not end with %s\n", file, suffix) } } }
Output
report.pdf does not end with .txt
image.png does not end with .txt
notes.txt ends with .txt
archive.zip does not end with .txt
Common Pitfalls
Common mistakes when using strings.HasSuffix include:
- Forgetting to import the
stringspackage, which causes a compile error. - Confusing
HasSuffixwithHasPrefix, which checks the start of a string. - Passing empty strings as suffix, which always returns
truebecause every string ends with an empty string.
Here is an example showing a wrong and right usage:
go
package main import ( "fmt" "strings" ) func main() { text := "example.go" // Wrong: forgetting to import strings causes error // result := HasSuffix(text, ".go") // undefined: HasSuffix // Right: use strings.HasSuffix result := strings.HasSuffix(text, ".go") fmt.Println(result) // true // Empty suffix returns true emptySuffix := "" fmt.Println(strings.HasSuffix(text, emptySuffix)) // true }
Output
true
true
Quick Reference
| Function | Description | Returns |
|---|---|---|
| strings.HasSuffix(s, suffix) | Checks if string s ends with suffix | bool (true or false) |
| Parameters | s: main string, suffix: ending substring | N/A |
| Return value | true if s ends with suffix, else false | bool |
Key Takeaways
Use strings.HasSuffix(s, suffix) to check if s ends with suffix in Go.
Always import the strings package before using HasSuffix.
HasSuffix returns true if suffix is empty because every string ends with an empty string.
Do not confuse HasSuffix with HasPrefix; they check different parts of the string.
Use HasSuffix in conditions to easily filter or validate string endings.