Check if a string starts with a substring

package main

import (
    "strings"
)

func main() {
    strings.HasPrefix("flavio", "fla") // true
}

play

Check if a string ends with a substring

package main

import (
    "strings"
)

func main() {
    strings.HasSuffix("flavio", "vio") // true
}

play

Calculate the maximum string length in a slice of strings

// calculatemaxwidth given a slice of strings calculates the maximum
// length
func calculatemaxwidth(lines []string) int {
    w := 0
    for _, l := range lines {
        len := utf8.RuneCountInString(l)
        if len > w {
            w = len
        }
    }

    return w
}

Comparing strings case insensitive

Instead of running ToUpper() or ToLower() from the strings or bytes packages, use strings.EqualFold() or bytes.EqualFold(), because they are guaranteed to work across all languages.

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
}

Pssst! Also check my latest YouTube video



I am writing a book on how to create a successful blog as a developer.
It will be released late February.
Signup to my newsletter to get 2/3 free chapters in your inbox in the next few weeks!