You could define multiple types:

type bySubtotal []directory
type byName []directory

which have different Sort methods.

You could also define a type that includes a func(d0, d1 directory)
bool. The SortKeys example in the sort package docs
(https://golang.org/pkg/sort/#example__sortMultiKeys) covers this.

Personally, these days, I'd use sort.Slice and use it with two
different comparison functions.

On Tue, Nov 7, 2017 at 5:38 PM, rob <drrob...@gmail.com> wrote:
> Hi.  I am trying to sort a slice of a struct using one of two different
> fields.
>
> type directory struct {
>     name     string
>     subtotal int64
> }
>
> type dirslice []directory
>
> I want to sort a var of type dirslice by either name or subtotal.  I
> understand how to sort by one of those, by defining
>
> func (ds dirslice) Less(i, j int) bool {
>     return ds[i].subtotal < ds[j].subtotal
> }
>
> func (ds dirslice) Swap(i, j int) {
>     ds[i], ds[j] = ds[j], ds[i]
> }
>
> func (ds dirslice) Len() int {
>     return len(ds)
> }
>
> But I'm struggling w/ how to have a method that can use a different version
> of Swap, depending upon what I want.
>
> thanks,
>
> Rob Solomon
>
> --
> 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+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to