🏁 Check if a string starts with a substring in Go

May 11, 2021
introduction strings

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

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

✍️ Write to a file in Go

Learn how to write any data to a file
introduction file