英文:
How to sort a slice of version strings in Go
问题
我有一个包含String
类型版本的数组,需要进行排序,但当前的排序方法排序结果不正确。
apiVersions := []string{"1.4", "1.12", "1.21", "1.8"}
对apiVersions
进行排序后,数组的顺序应该是["1.4", "1.8", "1.12", "1.21"]
,而不是["1.12", "1.21", "1.4", "1.8"]
。
英文:
I have array full of versions of type String
& need to sort, but current sort method is sorting it incorrectly
apiVersions := []string{"1.4", "1.12", "1.21", "1.8"}
On sorting apiVersions
, the array looks like ["1.12", "1.21", "1.4", "1.8"]
instead of ["1.4", "1.8", "1.12", "1.21"]
答案1
得分: 1
你应该使用标准的Go语义版本比较包来执行此操作,而不是重新发明轮子。首先,使用hashicorp/go-version包来语义比较两个版本字符串。
package main
import (
"fmt"
"sort"
"github.com/hashicorp/go-version"
)
type byVersion []string
func (s byVersion) Len() int {
return len(s)
}
func (s byVersion) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byVersion) Less(i, j int) bool {
v1, err := version.NewVersion(s[i])
if err != nil {
panic(err)
}
v2, err := version.NewVersion(s[j])
if err != nil {
panic(err)
}
return v1.LessThan(v2)
}
func main() {
versions := []string{"1.4", "1.12", "1.21", "1.8"}
sort.Sort(byVersion(versions))
fmt.Println(versions)
}
将会产生预期的结果。
[1.4 1.8 1.12 1.21]
英文:
You should probably use one of the standard Go semantic version compare packages to perform this, rather than re-inventing the wheel. For starters, use the hashicorp/go-version package to semantically compare two version strings
package main
import (
"fmt"
"sort"
"github.com/hashicorp/go-version"
)
type byVersion []string
func (s byVersion) Len() int {
return len(s)
}
func (s byVersion) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byVersion) Less(i, j int) bool {
v1, err := version.NewVersion(s[i])
if err != nil {
panic(err)
}
v2, err := version.NewVersion(s[j])
if err != nil {
panic(err)
}
return v1.LessThan(v2)
}
func main() {
versions := []string{"1.4", "1.12", "1.21", "1.8"}
sort.Sort(byVersion(versions))
fmt.Println(versions)
}
produces the desired result as expected.
[1.4 1.8 1.12 1.21]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论