Array and slice data types

Because you're using a slice, not an array.

That is a slice:

var av = []int{1,5,2,3,7}

And those are arrays:

var av = [...]int{1,5,2,3,7}
var bv = [5]int{1,5,2,3,7}

If you try to compile:

var av = [...]int{1,5,2,3,7}
fmt.Println(av)
sort.Ints(av)
fmt.Println(av)

, you will get an error:

cannot use av (type [5]int) as type []int in function argument

as sort.Ints expects to receive a slice []int.


See "Slices: usage and internals"

var av = []int{1,5,2,3,7}

That is a slice, not an array.

A slice literal is declared just like an array literal, except you leave out the element count.

That explains why the sort function will modify the content of what is referenced by the slice.

As commented below by Kirk, sort.Ints will give you an error if you passed it an array instead of a slice.

func Ints(a []int)

[]int{1,5,2,3,7} is not an array. An array has it's length in it's type, like [5]int{1,5,2,3,7}.

Make a copy of the slice and sort it instead:

a := []int{1,5,2,3,7}
sortedA := make([]int, len(a))
copy(sortedA, a)
sort.Ints(sortedA)
fmt.Println(a)
fmt.Println(sortedA)