OneBite.Dev - Coding blog in a bite size

sort items in array by asc in Go

Code snippet on how to sort items in array by asc in Go

  package main
  
  import (
  	"fmt"
  	"sort"
  )
  
  func main(){
  	mySlice := []int{5, 4, 3, 2, 1}
  	// Sort int slice
  	sort.Ints(mySlice)
  	fmt.Println(mySlice)
  }

This code sorts an array of integers in ascending order. The first line, package main, tells the compiler we are in the main package, which provides an entry point for our program. The second line imports two packages, fmt and sort. fmt is the standard library package that allows us to print our data to the terminal and sort is a package that provides generic functions to sort our data. We create a variable mySlice that holds an array of integer values. We can then use the sort.Ints() function to sort our slice of data. We then call fmt.Println which prints the sorted array to the terminal.

go