Sort an array of strings by length

This Go example program illustrates sorting strings by length.

package main

import (

type Animals []string

func (a Animals) Len() int {
        return len(a)

func (a Animals) Swap(i, j int) {
        a[i], a[j] = a[j], a[i]

func (a Animals) Less(i, j int) bool {
        return len(a[i]) < len(a[j])

func main() {
        test := []string{
        for _, j := range (test) {
                fmt.Println (j)


Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer