如何比较golang中的两个版本号字符串

JVK*_*JVK 18 go

我有两个字符串(它们实际上是版本号,它们可以是任何版本号)

a := "1.05.00.0156"  
b := "1.0.221.9289"
Run Code Online (Sandbox Code Playgroud)

我想比较哪一个更大.如何在golang中做到这一点?

mcu*_*ros 13

前段时间我创建了一个版本比较库:https://github.com/mcuadros/go-version

version.CompareSimple("1.05.00.0156", "1.0.221.9289")
//Returns: 1
Run Code Online (Sandbox Code Playgroud)

好好享受!


pet*_*rSO 9

这是一个通用的解决方案.

package main

import "fmt"

func VersionOrdinal(version string) string {
    // ISO/IEC 14651:2011
    const maxByte = 1<<8 - 1
    vo := make([]byte, 0, len(version)+8)
    j := -1
    for i := 0; i < len(version); i++ {
        b := version[i]
        if '0' > b || b > '9' {
            vo = append(vo, b)
            j = -1
            continue
        }
        if j == -1 {
            vo = append(vo, 0x00)
            j = len(vo) - 1
        }
        if vo[j] == 1 && vo[j+1] == '0' {
            vo[j+1] = b
            continue
        }
        if vo[j]+1 > maxByte {
            panic("VersionOrdinal: invalid version")
        }
        vo = append(vo, b)
        vo[j]++
    }
    return string(vo)
}

func main() {
    versions := []struct{ a, b string }{
        {"1.05.00.0156", "1.0.221.9289"},
        // Go versions
        {"1", "1.0.1"},
        {"1.0.1", "1.0.2"},
        {"1.0.2", "1.0.3"},
        {"1.0.3", "1.1"},
        {"1.1", "1.1.1"},
        {"1.1.1", "1.1.2"},
        {"1.1.2", "1.2"},
    }
    for _, version := range versions {
        a, b := VersionOrdinal(version.a), VersionOrdinal(version.b)
        switch {
        case a > b:
            fmt.Println(version.a, ">", version.b)
        case a < b:
            fmt.Println(version.a, "<", version.b)
        case a == b:
            fmt.Println(version.a, "=", version.b)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

1.05.00.0156 > 1.0.221.9289
1 < 1.0.1
1.0.1 < 1.0.2
1.0.2 < 1.0.3
1.0.3 < 1.1
1.1 < 1.1.1
1.1.1 < 1.1.2
1.1.2 < 1.2
Run Code Online (Sandbox Code Playgroud)


小智 8

Hashicorp提供了一个很好的解决方案 - https://github.com/hashicorp/go-version

import github.com/hashicorp/go-version
v1, err := version.NewVersion("1.2")
v2, err := version.NewVersion("1.5+metadata")
// Comparison example. There is also GreaterThan, Equal, and just
// a simple Compare that returns an int allowing easy >=, <=, etc.
if v1.LessThan(v2) {
    fmt.Printf("%s is less than %s", v1, v2)
}
Run Code Online (Sandbox Code Playgroud)


小智 5

以下是一些用于版本比较的库:

  1. https://github.com/blang/semver
  2. https://github.com/Masterminds/semver
  3. https://github.com/hashicorp/go-version
  4. https://github.com/mcuadros/go-version

我用过blang/semver。例如: https: //play.golang.org/p/1zZvEjLSOAr

 import github.com/blang/semver/v4
 
  v1, err := semver.Make("1.0.0-beta")
  v2, err := semver.Make("2.0.0-beta")
 
  // Options availabe
  v1.Compare(v2)  // Compare
  v1.LT(v2)       // LessThan
  v1.GT(v2)       // GreaterThan
Run Code Online (Sandbox Code Playgroud)