[Golang] Code snippets - Semver comparison

To make the project backward-compatible, a common util function for comparing the semantic version is indispensable. Here is a Golang solution implemented by leveraging go-semver package.

package utils

import "github.com/coreos/go-semver/semver"

// CompareSemanticVersion compares two string written in semver format
// return 0 indicates that the first version equals to the second version
// return 1 indicates that the first version is greater than the second version
// return -1 indicates that the first version is less than the second version
func CompareSemanticVersion(current, last string) int {
	if current == last {
		return 0
	}

	currentVersion := semver.New(current)
	lastVersion := semver.New(last)
	if currentVersion.LessThan(*lastVersion) {
		return -1
	}
	return 1
}

The unit test:

package utils

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func Test_CompareSemanticVersion(t *testing.T) {
	tests := []struct {
		name     string
		current  string
		last     string
		expected int
	}{
		{
			name:     "current version = last version",
			current:  "2.15.0",
			last:     "2.15.0",
			expected: 0,
		},
		{
			name:     "current version < last version",
			current:  "2.15.0",
			last:     "2.15.1",
			expected: -1,
		},
		{
			name:     "current version > last version",
			current:  "2.15.0",
			last:     "2.14.1",
			expected: 1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			actual := CompareSemanticVersion(tt.current, tt.last)
			require.Equal(t, tt.expected, actual)
		})
	}
}

If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !