🏁 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

πŸ—ƒοΈ 3 ways to pretty print JSON in Go

Learn how to generate JSON with indentation
introduction json strings

πŸ—ΊοΈ Convert map to JSON in Go

August 1, 2021
introduction json strings

πŸ”’ Convert int to string in Go

Learn how to convert int, int64, int32, int16 or int8 to a decimal, hexadecimal octal or binary string
introduction numbers integer