To check if the string ends with a specified suffix in Golang, you can use the “HasSuffix()” function. The HasSuffix() function is “used to check whether a given string ends with a specified Suffix string.” It returns True if the given string ends with the specified Suffix string; otherwise, it returns False.
The HasSuffix() and HasPrefix() functions are “used to check if a string ends or starts with a particular set of characters, respectively.”
Syntax
func HasSuffix(s, prefix string) bool
Parameters
- s: It is an input string.
- prefix: It is a string that represents the suffix.
Return value
The return type of this function is of the bool type.
Example 1
package main
import (
"fmt"
"strings"
)
func main() {
// Initializing the Strings
s := "Golang is a modern programming language."
// Using the HasSuffix Function
result1 := strings.HasSuffix(s, "language.")
result2 := strings.HasSuffix(s, "technology.")
// Display the HasSuffix Output
fmt.Println("Given String ends with 'language.'? :", result1)
fmt.Println("Given String ends with 'technology.'? :", result2)
}
Output
Given String ends with 'language.'? : true
Given String ends with 'technology.'? : false
Example 2
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
s1 := "Go is a great programming language!"
s2 := "OpenAI is leading in AI research and development."
// Checking if the given strings end with the specified suffixes
// Using HasSuffix() function
res1 := strings.HasSuffix(s1, "language!")
res2 := strings.HasSuffix(s1, "Python!")
res3 := strings.HasSuffix(s2, "development.")
res4 := strings.HasSuffix(s2, "science.")
res5 := strings.HasSuffix("Welcome to OpenAI", "OpenAI")
res6 := strings.HasSuffix("Exploring new technologies", "technologies")
res7 := strings.HasSuffix("Embrace the future with AI", "past")
// Displaying results
fmt.Println("Does String 1 end with 'language!'? ", res1)
fmt.Println("Does String 1 end with 'Python!'? ", res2)
fmt.Println("Does String 2 end with 'development.'? ", res3)
fmt.Println("Does String 2 end with 'science.'? ", res4)
fmt.Println("Does 'Welcome to OpenAI' end with 'OpenAI'? ", res5)
fmt.Println("Does 'Exploring new technologies' end with 'technologies'? ", res6)
fmt.Println("Does 'Embrace the future with AI' end with 'past'? ", res7)
}
Output
That’s it!
Related posts
Check If String is Alphanumeric in Golang
Check If String is Empty in Golang
Check If the String Starts with Specified Prefix in Golang

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.