如何在Go中对版本字符串切片进行排序

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

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]

huangapple
  • 本文由 发表于 2022年10月12日 20:41:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/74042013.html
匿名

发表评论

匿名网友

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

确定