在Go语言中,可以使用函数或方法进行排序。

huangapple go评论75阅读模式
英文:

Sort with a function or method in Go?

问题

sort包提供了以下函数来对内置的切片类型进行排序:

  • sort.Ints(a []int)
  • sort.Float64s(a []float64)
  • sort.Strings(a []string)

它还提供了以下类型,用于将内置的切片类型转换为具有Len()Less()Search()Sort()Swap()方法的命名类型:

  • sort.IntSlice
  • sort.Float64Slice
  • sort.StringSlice

这意味着我可以像这样对整数切片进行排序...

// 函数方式
slice := []int{5, 4, 3, 2, 1}
sort.Ints(slice) // 原地排序

或者像这样...

// 方法方式
slice := sort.IntSlice{5, 4, 3, 2, 1}
slice.Sort() // 也是原地排序

在排序时,使用函数还是方法更好?是否有某种情况下应该优先选择其中一种形式?

英文:

The sort package provides these functions for sorting the builtin slice types:

  • sort.Ints(a []int)
  • sort.Float64s(a []float64)
  • sort.Strings(a []string)

It also provides these types for converting the builtin slice types to named types with Len(), Less(), Search(), Sort(), and Swap() methods:

  • sort.IntSlice
  • sort.Float64Slice
  • sort.StringSlice

That means I can sort a slice of ints like this...

// Function
slice := []int{5, 4, 3, 2, 1}
sort.Ints(slice) // sort in place

or like this...

// Method
slice := sort.IntSlice{5, 4, 3, 2, 1}
slice.Sort() // also sort in place

Is it preferable to sort with a function or a method? Are there times when one form should be preferred over the other?

答案1

得分: 7

sort.Ints(x)的定义实际上是sort.Sort(sort.IntSlice(x)),所以实际上并没有什么区别。前者更短,所以我会使用它。

英文:

The definition of sort.Ints(x) is literally sort.Sort(sort.IntSlice(x)) so it really doesn't matter. The former is shorter, so I'd use that.

huangapple
  • 本文由 发表于 2014年5月3日 06:51:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/23438124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定