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
Import the package in your code
In your code, import the semver
package like this:
import "golang.org/x/mod/semver"
Use it in your code:
v := "v1.24.6"
w := "v1.25.0"
semver.Compare(v, w)
The rules are simple:
-
-1
ifv < w
-
1
ifv > w
-
0
ifv == 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")
}
}
That’s it! Pretty neat and super straightforward. With just one function, you can easily handle semantic version comparisons with Go.
Top comments (0)