0
0
GoHow-ToBeginner · 3 min read

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 strings package, which causes a compile error.
  • Confusing HasSuffix with HasPrefix, which checks the start of a string.
  • Passing empty strings as suffix, which always returns true because 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

FunctionDescriptionReturns
strings.HasSuffix(s, suffix)Checks if string s ends with suffixbool (true or false)
Parameterss: main string, suffix: ending substringN/A
Return valuetrue if s ends with suffix, else falsebool

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.