strings.HasSuffix() method in Golang

The HasSuffix() method is a part of the strings package in the Go language. This post will discuss the Golang HasSuffix() method in detail.

  • Method declaration – func HasSuffix(s, suffix string) bool
  • What does it do? It checks whether the string s( passed in the first argument ) ends with the suffix string ( passed in the second argument ) or not
  • What does it return? It will return true if string s ends with the suffix string. Otherwise, it will return false

So, if you want to know whether a specified string ends with a string or not, then HasSuffix() method will do the trick for you.

package main

import (
	"fmt"
	"strings"
)

func main() {

	isSuffix1 := strings.HasSuffix("codekru", "code")
	isSuffix2 := strings.HasSuffix("codekru", "kru")

	fmt.Println("is codekru ends with code?", isSuffix1)
	fmt.Println("is codekru ends with kru?", isSuffix2)

}

Output –

is codekru ends with code? false
is codekru ends with kru? true
Internal implementation of the Golang’s HasSuffix() method
func HasSuffix(s, suffix string) bool {
	return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}

Its implementation is almost similar to the HasPrefix() method. But we will tell you about what’s happening here.

  • First, it checks whether the length of the string s is greater than or equal to the suffix string or not. If not, then it will return false.
  • And then, if the length check has passed, it will check whether string s ends with the suffix string or not by using this code s[len(s)-len(suffix):] == suffix, and if this check passes, then the function will return true. Otherwise, it will return false.

The What If scenarios

Q – What if we use an empty string as the suffix string?

It will return true as every string ends with an empty string, as illustrated by the below program.

package main

import (
	"fmt"
	"strings"
)

func main() {

	isSuffix := strings.HasSuffix("codekru", "")

	fmt.Println(isSuffix)

}

Output –

true
Q – What if we don’t initialize both strings and use the HasSuffix() method?

An uninitialized string will be treated as an empty string. So, it will be like using two empty strings within the HasSuffix() method arguments.

package main

import (
	"fmt"
	"strings"
)

func main() {

	isSuffix := strings.HasSuffix("", "")

	fmt.Println(isSuffix)

}

Output –

true

Please visit this link to learn more about the Strings in Go language and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Articles –
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *