Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

🏁 Check if a string starts with a substring in Go

introduction strings

Please consider supporting us by disabling your ad blocker

It’s really simple to check if a given string starts with another substring in Go. In many programming languages, there is a startsWith() function to do this. In Go, we have HasPrefix() from the strings package. It returns true when a substring is the prefix of a string or false otherwise.

package main

import (
    "fmt"
    "strings"
)

const name = "GOSAMPLES"

func main() {
    fmt.Printf("GO is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "GO"))
    fmt.Printf("SAMPLES is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "SAMPLES"))
}

Output:

GO is at the beginning of GOSAMPLES: true
SAMPLES is at the beginning of GOSAMPLES: false

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool