Check if the String starts with specified prefix in Golang

In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.
In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix. It is defined under the strings package so, you have to import strings package in your program for accessing HasPrefix function.


func HasPrefix(str, pre string) bool

Here, str is the original string and pre is a string which represents the prefix. The return type of this function is of the bool type. Let us discuss this concept with the help of an example:






// Go program to illustrate how to check
// the given string starts with the
// specified prefix
package main
import (
// Main function
func main() {
    // Creating and initializing strings
    // Using shorthand declaration
    s1 := "I am working as a Technical content writer in GeeksforGeeks!"
    s2 := "I am currently writing articles on Go language!"
    // Checking the given strings starts with the specified prefix
    // Using HasPrefix() function
    res1 := strings.HasPrefix(s1, "I")
    res2 := strings.HasPrefix(s1, "My")
    res3 := strings.HasPrefix(s2, "I")
    res4 := strings.HasPrefix(s2, "We")
    res5 := strings.HasPrefix("GeeksforGeeks", "Welcome")
    res6 := strings.HasPrefix("Welcome to GeeksforGeeks", "Welcome")
    // Displaying results
    fmt.Println("Result 1: ", res1)
    fmt.Println("Result 2: ", res2)
    fmt.Println("Result 3: ", res3)
    fmt.Println("Result 4: ", res4)
    fmt.Println("Result 5: ", res5)
    fmt.Println("Result 6: ", res6)



Result 1:  true
Result 2:  false
Result 3:  true
Result 4:  false
Result 5:  false
Result 6:  true
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.