go-version
是一个 Go 语言的库,用于处理和比较版本号。它可以解析版本号字符串并提供版本比较的功能,非常适合需要管理和比较软件版本的场景。
作用
使用场景
项目地址:https://github.com/hashicorp/go-version
使用go-version
解析的版本号需要遵循SemVer规范
代码片段:
gofor _, item := range []string{"v1.2.9", "1.2", "1.5+metadata", "1.4-beta"} {
ver, _ := version.NewVersion(item)
println("==================")
println("String", ver.String())
println("Original", ver.Original())
println("Prerelease", ver.Prerelease())
println("Metadata", ver.Metadata())
}
运行结果:
================== String 1.2.9 Original v1.2.9 Prerelease Metadata ================== String 1.2.0 Original 1.2 Prerelease Metadata ================== String 1.5.0+metadata Original 1.5+metadata Prerelease Metadata metadata ================== String 1.4.0-beta Original 1.4-beta Prerelease beta Metadata
代码片段:
gov1, _ := version.NewVersion("1.2")
v2, _ := version.NewVersion("1.5+metadata")
println("GreaterThanOrEqual", v1.GreaterThanOrEqual(v2))
println("GreaterThan", v1.GreaterThan(v2))
println("Equal", v1.Equal(v2))
println("LessThanOrEqual", v1.LessThanOrEqual(v2))
println("LessThan", v1.LessThan(v2))
println("Compare", v1.Compare(v2))
运行结果:
GreaterThanOrEqual false GreaterThan false Equal false LessThanOrEqual true LessThan true Compare -1
代码片段:
gov1, _ := version.NewVersion("1.2")
// Constraints example.
constraints, _ := version.NewConstraint(">= 1.0, < 1.4")
if constraints.Check(v1) {
println(v1.String(), "satisfies constraints", constraints.String())
} else {
println(v1.String(), "unsatisfied constraints", constraints.String())
}
运行结果:
1.2.0 satisfies constraints >= 1.0, < 1.4
代码片段:
goversionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"}
versions := make([]*version.Version, len(versionsRaw))
for i, raw := range versionsRaw {
v, _ := version.NewVersion(raw)
versions[i] = v
}
sort.Sort(version.Collection(versions))
for _, item := range versions {
println(item.String())
}
运行结果:
0.7.1 1.1.0 1.4.0-beta 1.4.0 2.0.0
本文作者:蒋固金
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!