Skip to content

Instantly share code, notes, and snippets.

@icio
Created February 21, 2023 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icio/8ade26bd518f61ed6b82e9b458354945 to your computer and use it in GitHub Desktop.
Save icio/8ade26bd518f61ed6b82e9b458354945 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
"github.com/google/go-cmp/cmp"
)
type Response struct {
Meta Meta
Summary Summary
Results []Result
}
type Meta struct {
Pages int
}
type Summary struct {
First, Last string
Count int
}
type Result struct {
ID string
Amount int64
}
func main() {
got := Response{
Meta: Meta{
Pages: 10,
},
Summary: Summary{
First: "a",
Last: "z",
Count: 26,
},
Results: []Result{
{ID: "a", Amount: 0},
{ID: "b", Amount: 1},
{ID: "c", Amount: 2},
},
}
fmt.Println("1", diff(got, Response{Meta: Meta{Pages: 20}}))
fmt.Println("2", diff(got, Response{Results: []Result{{ID: "a"}, {ID: "B"}, {ID: "c"}, {ID: "d"}}}))
}
func diff(got, want Response) string {
d := cmp.Diff(
want, got,
cmp.FilterPath(
func(path cmp.Path) bool {
wantField, _ := path[len(path)-1].Values()
return wantField.Kind() != reflect.Invalid && wantField.IsZero()
},
cmp.Ignore(),
),
)
if d == "" {
return "(same)"
}
return "(-want +got):\n" + d
}
@icio
Copy link
Author

icio commented Feb 21, 2023

Output: https://go.dev/play/p/eSgea433jii

1 (-want +got):
  main.Response{
- 	Meta: main.Meta{Pages: 20},
+ 	Meta: main.Meta{Pages: 10},
  	... // 2 ignored fields
  }

2 (-want +got):
  main.Response{
  	... // 2 ignored fields
  	Results: []main.Result{
  		{ID: "a"},
  		{
- 			ID: "B",
+ 			ID: "b",
  			... // 1 ignored field
  		},
  		{ID: "c"},
- 		{ID: "d"},
  	},
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment