A Go library for tracking and comparing struct revisions. It provides a simple interface to detect changes between two struct instances, with support for field inclusion/exclusion and easy integration into your projects.
- Compare two structs and get a list of changed fields
- Ignore unexported fields automatically
- Include or exclude specific fields from comparison
- Simple API for checking if structs are identical or changed
go get github.com/go-universal/revision
package main
import (
"fmt"
"github.com/go-universal/revision"
)
type User struct {
ID int
Name string
Email string
age int // unexported, will be ignored
}
func main() {
oldUser := User{ID: 1, Name: "Alice", Email: "[email protected]", age: 30}
newUser := User{ID: 1, Name: "Alice Smith", Email: "[email protected]", age: 31}
rev := revision.NewRevision(oldUser, newUser)
if !rev.IsValid() {
panic("Invalid revision: structs must be of the same type")
}
changes := rev.Changes()
for _, c := range changes {
fmt.Printf("Field: %s, Old: %v, New: %v\n", c.Field, c.OldValue, c.NewValue)
}
fmt.Println("IsSame:", rev.IsSame()) // false
fmt.Println("IsChanged:", rev.IsChanged()) // true
}
You can specify which fields to include or exclude in the comparison:
rev := revision.NewRevision(
oldUser,
newUser,
revision.WithIncludeFields("Name"), // Only compare the Name field
)
// Or exclude specific fields
rev = revision.NewRevision(
oldUser,
newUser,
revision.WithExcludeFields("Email"), // Compare all except Email
)
IsValid() bool
β Returns true if both structs are valid and of the same type.Changes() Changes
β Returns a slice of changed fields (see below).IsSame() bool
β Returns true if there are no changes.IsChanged() bool
β Returns true if there are any changes.
Field string
β The name of the changed fieldOldValue any
β The old valueNewValue any
β The new value
Contains(field string) bool
β Returns true if the field is in the changesFind(field string) (any, any, bool)
β Returns old/new values and true if foundLength() int
β Number of changed fieldsFields() []string
β List of changed field names
This project is licensed under the ISC License. See the LICENSE file for details.