sort int slice in golang

To sort an int slice in Go, you can use the built-in sort package. Here are the steps to accomplish this:

  1. Import the sort package: Begin by importing the sort package in your Go program. You can do this by adding the following line at the beginning of your code:
import "sort"
  1. Create an int slice: Next, create an int slice that you want to sort. You can define and initialize the slice with some values like this:
numbers := []int{9, 5, 2, 7, 1, 4}
  1. Use the sort.Ints() function: To sort the int slice, use the sort.Ints() function provided by the sort package. Pass the int slice as an argument to this function, like so:
sort.Ints(numbers)
  1. Print the sorted slice: Finally, you can print the sorted int slice to see the result. You can use the fmt.Println() function for this:
fmt.Println(numbers)

Putting it all together, here's an example of how the code would look:

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{9, 5, 2, 7, 1, 4}
    sort.Ints(numbers)
    fmt.Println(numbers)
}

When you run this code, it will output the sorted int slice: [1 2 4 5 7 9].