Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sort strings by length

package main

import (
	"fmt"
	"sort"
)

func main() {
	animals := []string{"snail", "dog", "cow", "elephant", "chicken", "mouse"}
	fmt.Println(animals)

	sort.Strings(animals)
	fmt.Println(animals)

	sort.Slice(animals, func(i, j int) bool {
		return len(animals[i]) < len(animals[j])
	})
	fmt.Println(animals)
}
[snail dog cow elephant chicken mouse]
[chicken cow dog elephant mouse snail]
[cow dog mouse snail chicken elephant]