Cheat sheet

Check if the string starts with a substring

package main

import ( “strings” )

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

play

Check if the string ends with a substring

package main

import ( “strings” )

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

play

Calculate the maximum string length in a string slice

// 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
        }
    }
<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">w</span>

}

Compare case-insensitive strings

Instead of runningToUpper()orToLower()FromstringsorbytesPackaging, usestrings.EqualFold()orbytes.EqualFold(), Because it can be guaranteed that they can be used in all languages.

package main

import ( “bytes” “fmt” )

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


More tutorials: