DEV Community

Joy Biswas
Joy Biswas

Posted on

Semantic Version Comparison with Go

#go

I was writing a script to update Go to a newer version if an update was available. For that, I needed to compare the currently installed version with the latest remote version.Then I came across golang.org/x/mod/semver and used it to compare the local and remote versions.

Follow the steps below to get started.

Install the semver module

go get golang.org/x/mod/semver
Enter fullscreen mode Exit fullscreen mode

Import the package in your code

In your code, import the semver package like this:

import "golang.org/x/mod/semver"
Enter fullscreen mode Exit fullscreen mode

Use it in your code:

v := "v1.24.6"
w := "v1.25.0"

semver.Compare(v, w)
Enter fullscreen mode Exit fullscreen mode

The rules are simple:

  • -1 if v < w
  • 1 if v > w
  • 0 if v == w

Full Example

Here’s the complete code to check if your local Go version needs an update:

package main

import (
    "fmt"

    "golang.org/x/mod/semver"
)

func main() {
    local := "v1.24.6"
    remote := "v1.25.0"

    switch semver.Compare(local, remote) {
    case -1:
        fmt.Println("Update available")
    case 1:
        fmt.Println("You're already up to date")
    case 0:
        fmt.Println("Both local and remote version are same")
    }
}
Enter fullscreen mode Exit fullscreen mode

That’s it! Pretty neat and super straightforward. With just one function, you can easily handle semantic version comparisons with Go.

Top comments (0)