Sort Primitives (strings, ints, and floats) in Go

Jeff Roberts
InstructorJeff Roberts

Share this video with your friends

Send Tweet

There are numerous ways to sort slices in Go.

The simplest way uses some basic built-in functions from Go's sort package to allow you to easily sort slices of primitives, that being Strings, Ints and Float64s. Using these sort functions, we don't have control over the sort order as the data will be sorted in ascending alphabetical (for strings) or ascending numerical (for Ints and Float64s) order.

In this lesson, we will take a quick look at the easiest way to sort slices of primitives. We will learn about using some of the handy built-in functions in Go's sort package, including:

  • sort.Strings: Sorting a slice of strings
  • sort.Ints: Sorting a slice of ints
  • sort.Float64s: Sorting a slice of float64s
Joseph Michael Casey
Joseph Michael Casey
~ a year ago

It looks like the link to your code for this lesson is not available.

https://github.com/JeffBNimble/GoLessons/tree/master/Array-Sort

Jeff Roberts
Jeff Robertsinstructor
~ a year ago

Joseph, I'm very sorry for this and thank you very much for catching this. The code for numerous sort lessons has been pushed to GitHub. I have a couple more sort lessons in the works, so watch for those.

Joseph Michael Casey
Joseph Michael Casey
~ a year ago

Hey Jeff,

How are you running your code? I tried go run sort_primitives.go to no avail. Any suggestions on running the API server you show in the video?

Jeff Roberts
Jeff Robertsinstructor
~ a year ago

Hi Joseph, I'm really sorry for the trouble. The feedback is very valuable. I will update instructions on the GitHub repo to make it easier to run. Until then, here is what you need to do.

The reason that it is not obvious is that this GitHub project actually supports multiple lessons. So, if you locate main.go, you'll notice that in the main func, there is currently a call to sortSlices(). If you look at the sort_slices.go and the sort_primitives.go, you'll see the code for the different lessons.

If you want to run the code for the Sort Primitives lesson, change the main func in main.go to call sortPrimitives(). If you want to run the code for the Sort Slices lesson, change the main func in main.go to call sortSlices().

Hopefully, that clears up the confusion. And again, thank you for the feedback. I will get these instructions updated in the project README.