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/revisionpackage 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.