How to check if a string starts with a substring in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I’m gonna show you how do you check if a string starts with a substring in golang, here we will use the golang strings.HasPrefix() method to check string start with a specific string or not.

The strings.HasPrefix() help us to know the string prefix, it will return a true substring match with a string starting characters.

Let’s start today’s tutorial How do I check if a string starts with a substring in golang?

Here we are going to use the golang string package to use the HasPrefix() method.

The HasPrefix() method expects string in the first parameter, and substring and second parameter when it will match, it will return true else false.

let’s write a code.

package main

import (
	"strings"
)

func main() {
	strings.HasPrefix("foobar", "foo") // true
}

When you run the above program, it will print true in the golang console.

let’s check the output.

check, string starts with a substring, golang

Try it yourself

All the best 👍

Follow me on Twitter