TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Golang Sort Slices: Interface

These Go examples use the sort package and sort elements. They invoke the Strings and Sort methods.

Sort. Data often comes with no order.

It is unordered. It is unorganized. Computer algorithms reorder elements to make them sequential.

With sort, a package, we gain many methods for reordering data. We can sort strings alphabetically with Strings(). For complex needs, we can use Sort and define an interface.

Strings. This method implements an ascending (low to high, alphabetical) sort of strings. So they go from A to Z. We must add the "sort" package to our import block.

In-place: The Strings method operates in-place. So we do not need to assign anything to it—it modifies the slice.

Slice: The Strings method, as well as other methods in "sort," all operate on slices. This is the standard Go approach.

Result: The strings are sorted alphabetically—so "bird" comes first and "zebra" last.

Based on:

Golang 1.4

Golang program that uses sort, Strings method

package main

import (
    "fmt"
    "sort"
)

func main() {
    animals := []string{"cat", "bird", "zebra", "fox"}

    // Sort strings.
    sort.Strings(animals)

    // Print results.
    fmt.Println(animals)
}

Output

[bird cat fox zebra]

Sort strings by length. Here we specify how elements in a slice are sorted. We use the "type" keyword to create a type. We implement the sort.Interface on our ByLen type.

Len: This method is required by sort.Interface. It is used by the sort.Sort func.

Less: This compares two elements of the type. Here we use custom code to compare the lengths of two elements.

Swap: This is used by the sorting algorithm to swap two elements in the collection.

Result: The program sorts the strings by their lengths, from shortest to longest. They are not alphabetized.

Golang program that sorts strings by length

package main

import (
    "fmt"
    "sort"
)

// Implement length-based sort with ByLen type.
type ByLen []string
func (a ByLen) Len() int           { return len(a) }
func (a ByLen) Less(i, j int) bool { return len(a[i]) < len(a[j]) }
func (a ByLen) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    // These elements are not sorted.
    elements := []string{"ruby", "python", "java", "go"}

    // Sort the elements by length.
    sort.Sort(ByLen(elements))

    // Print results.
    fmt.Println(elements)
}

Output

[go ruby java python]

Important. Sorting is an important problem in computer languages. In Go we can use funcs like Strings() to sort simple collections.

With the sort Interface, and its funcs Len, Less and Swap, we can sort elements in more complex ways. Sorting in Go operates on slices.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf