Sorting slice of structs

427 views
Skip to first unread message

Sankar

unread,
Apr 10, 2018, 2:28:49 PM4/10/18
to golang-nuts
Hi

I have the following code:

type Point struct {
X    int
Name string
}

arr := []Point{
Point{1, "One"},
Point{3, "Three"},
Point{2, "Two"},
Point{4, "Four"},
}

log.Println("Before Sorting: ", arr)
sort.Slice(arr, func(i, j int) bool {
return arr[i].X < arr[i].X
})
log.Println("After Sorting: ", arr)

I wanted to see the slice of Point objects to be sorted after I called the sort function, but the slice remains unchanged. 

The play url is: 

Any help on how I can get arr sorted in the above code ?

Thanks.

Michael Jones

unread,
Apr 10, 2018, 2:33:21 PM4/10/18
to Sankar, golang-nuts
Change I i to I j 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Michael T. Jones
michae...@gmail.com

Burak Serdar

unread,
Apr 10, 2018, 2:33:37 PM4/10/18
to Sankar, golang-nuts
Simple mistake.

You have:
sort.Slice(arr, func(i, j int) bool {
return arr[i].X < arr[i].X
})

Instead use:
sort.Slice(arr, func(i, j int) bool {
return arr[i].X < arr[j].X
})

Jan Mercl

unread,
Apr 10, 2018, 2:35:00 PM4/10/18
to Sankar, golang-nuts

On Tue, Apr 10, 2018 at 8:29 PM Sankar <sankar.c...@gmail.com> wrote:

> Any help on how I can get arr sorted in the above code ?

--

-j

Sankar

unread,
Apr 10, 2018, 2:38:56 PM4/10/18
to golang-nuts
ah damn. Thanks  everyone :)

Michael Jones

unread,
Apr 10, 2018, 7:18:34 PM4/10/18
to Sankar, golang-nuts
We all saw it immediately ... because ... we remember having done it too. :-)

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages