go-cmp icon indicating copy to clipboard operation
go-cmp copied to clipboard

unhelpful output for difference in slices

Open seehuhn opened this issue 1 year ago • 1 comments

In the code below, Diff shows the following "differences" between two data structures:

main.Array{
  	main.Integer(0),
- 	s"<Array, 3 elements>",
+ 	s"<Array, 3 elements>",
  }

Since the + and - lines are the same, this is not very helpful. It would be nice if Diff would show the actual differences. Here is the code (also on the Go Playground):

package main

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/google/go-cmp/cmp"
)

type Integer int64

type Array []interface{}

func (x Array) String() string {
	res := []string{}
	res = append(res, "Array")
	res = append(res, strconv.FormatInt(int64(len(x)), 10)+" elements")
	return "<" + strings.Join(res, ", ") + ">"
}

func main() {
	a := Array{Integer(0), Array{float64(1), float64(2), float64(3)}}
	b := Array{Integer(0), Array{Integer(1), Integer(2), Integer(3)}}
	fmt.Println(cmp.Diff(a, b))
}

seehuhn avatar Jan 12 '24 11:01 seehuhn

Thanks for the concise report and reproduction. This suggest that the reporter should check if the String() output of an adjacent difference is identical. If so, to re-format the sub-value to ignore the String method.

dsnet avatar Jan 12 '24 18:01 dsnet