To check if a string starts with a specified Prefix string in Golang, you can use the “HasPrefix()” function. The HasPrefix() function is “used to check whether a given string begins with a specified Prefix string.” It returns True if the given string begins with the specified prefix string; otherwise, it returns False.
Syntax
func HasPrefix(s, prefix string) bool
Parameters
s: It is the given string.
Return value
It returns a Boolean value.
Example 1
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
s1 := "Programming in Go is rewarding."
s2 := "Go is a statically typed language."
s3 := "OpenAI is advancing AI research."
// Checking if the given strings start with the specified prefixes
// Using HasPrefix() function
res1 := strings.HasPrefix(s1, "Programming")
res2 := strings.HasPrefix(s1, "Coding")
res3 := strings.HasPrefix(s2, "Go")
res4 := strings.HasPrefix(s2, "Python")
res5 := strings.HasPrefix(s3, "OpenAI")
res6 := strings.HasPrefix(s3, "ClosedAI")
// Displaying results
fmt.Println("Does String 1 start with 'Programming'? ", res1)
fmt.Println("Does String 1 start with 'Coding'? ", res2)
fmt.Println("Does String 2 start with 'Go'? ", res3)
fmt.Println("Does String 2 start with 'Python'? ", res4)
fmt.Println("Does String 3 start with 'OpenAI'? ", res5)
fmt.Println("Does String 3 start with 'ClosedAI'? ", res6)
}
Output
Example 2
package main
import (
"fmt"
"strings"
)
func main() {
// Initializing the Strings
y := "Learning Go is a great experience!"
// Display the Strings
fmt.Println("Given String:", y)
// Using the HasPrefix Function
result1 := strings.HasPrefix(y, "Learning")
result2 := strings.HasPrefix(y, "Studying")
// Display the HasPrefix Output
fmt.Println("Given String has the prefix 'Learning'? :", result1)
fmt.Println("Given String has the prefix 'Studying'? :", result2)
}
Output
Given String: Learning Go is a great experience!
Given String has the prefix 'Learning'? : true
Given String has the prefix 'Studying'? : false
That’s it!
Related posts
Check If String is Alphanumeric in Golang
Check If String is Empty in Golang
Check If the String Ends with Specified Suffix 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.