Documentation

Overview

    Package cmp determines equality of values.

    This package is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal. It is intended to only be used in tests, as performance is not a goal and it may panic if it cannot compare the values. Its propensity towards panicking means that its unsuitable for production environments where a spurious panic may be fatal.

    The primary features of cmp are:

    • When the default behavior of equality does not suit the needs of the test, custom equality functions can override the equality operation. For example, an equality function may report floats as equal so long as they are within some tolerance of each other.

    • Types that have an Equal method may use that method to determine equality. This allows package authors to determine the equality operation for the types that they define.

    • If no custom equality functions are used and no Equal method is defined, equality is determined by recursively comparing the primitive kinds on both values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported fields are not compared by default; they result in panics unless suppressed by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared using the Exporter option.

    Index

    Examples

    Constants

    This section is empty.

    Variables

    This section is empty.

    Functions

    func Diff

    func Diff(x, y interface{}, opts ...Option) string

      Diff returns a human-readable report of the differences between two values: y - x. It returns an empty string if and only if Equal returns true for the same input values and options.

      The output is displayed as a literal in pseudo-Go syntax. At the start of each line, a "-" prefix indicates an element removed from x, a "+" prefix to indicates an element added from y, and the lack of a prefix indicates an element common to both x and y. If possible, the output uses fmt.Stringer.String or error.Error methods to produce more humanly readable outputs. In such cases, the string is prefixed with either an 's' or 'e' character, respectively, to indicate that the method was called.

      Do not depend on this output being stable. If you need the ability to programmatically interpret the difference, consider using a custom Reporter.

      Example (Testing)

        Use Diff to print out a human-readable report of differences for tests comparing nested or structured data.

        Output:
        
        MakeGatewayInfo() mismatch (-want +got):
          cmp_test.Gateway{
          	SSID:      "CoffeeShopWiFi",
        - 	IPAddress: s"192.168.0.2",
        + 	IPAddress: s"192.168.0.1",
          	NetMask:   {0xff, 0xff, 0x00, 0x00},
          	Clients: []cmp_test.Client{
          		... // 2 identical elements
          		{Hostname: "macchiato", IPAddress: s"192.168.0.153", LastSeen: s"2009-11-10 23:39:43 +0000 UTC"},
          		{Hostname: "espresso", IPAddress: s"192.168.0.121"},
          		{
          			Hostname:  "latte",
        - 			IPAddress: s"192.168.0.221",
        + 			IPAddress: s"192.168.0.219",
          			LastSeen:  s"2009-11-10 23:00:23 +0000 UTC",
          		},
        + 		{
        + 			Hostname:  "americano",
        + 			IPAddress: s"192.168.0.188",
        + 			LastSeen:  s"2009-11-10 23:03:05 +0000 UTC",
        + 		},
          	},
          }
        

        func Equal

        func Equal(x, y interface{}, opts ...Option) bool

          Equal reports whether x and y are equal by recursively applying the following rules in the given order to x and y and all of their sub-values:

          • Let S be the set of all Ignore, Transformer, and Comparer options that remain after applying all path filters, value filters, and type filters. If at least one Ignore exists in S, then the comparison is ignored. If the number of Transformer and Comparer options in S is greater than one, then Equal panics because it is ambiguous which option to use. If S contains a single Transformer, then use that to transform the current values and recursively call Equal on the output values. If S contains a single Comparer, then use that to compare the current values. Otherwise, evaluation proceeds to the next rule.

          • If the values have an Equal method of the form "(T) Equal(T) bool" or "(T) Equal(I) bool" where T is assignable to I, then use the result of x.Equal(y) even if x or y is nil. Otherwise, no such method exists and evaluation proceeds to the next rule.

          • Lastly, try to compare x and y based on their basic kinds. Simple kinds like booleans, integers, floats, complex numbers, strings, and channels are compared using the equivalent of the == operator in Go. Functions are only equal if they are both nil, otherwise they are unequal.

          Structs are equal if recursively calling Equal on all fields report equal. If a struct contains unexported fields, Equal panics unless an Ignore option (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option explicitly permits comparing the unexported field.

          Slices are equal if they are both nil or both non-nil, where recursively calling Equal on all non-ignored slice or array elements report equal. Empty non-nil slices and nil slices are not equal; to equate empty slices, consider using cmpopts.EquateEmpty.

          Maps are equal if they are both nil or both non-nil, where recursively calling Equal on all non-ignored map entries report equal. Map keys are equal according to the == operator. To use custom comparisons for map keys, consider using cmpopts.SortMaps. Empty non-nil maps and nil maps are not equal; to equate empty maps, consider using cmpopts.EquateEmpty.

          Pointers and interfaces are equal if they are both nil or both non-nil, where they have the same underlying concrete type and recursively calling Equal on the underlying values reports equal.

          Before recursing into a pointer, slice element, or map, the current path is checked to detect whether the address has already been visited. If there is a cycle, then the pointed at values are considered equal only if both addresses were previously visited in the same path step.

          Types

          type Indirect

          type Indirect struct {
          	// contains filtered or unexported fields
          }

            Indirect represents pointer indirection on the parent type.

            func (Indirect) String

            func (in Indirect) String() string

            func (Indirect) Type

            func (in Indirect) Type() reflect.Type

            func (Indirect) Values

            func (in Indirect) Values() (vx, vy reflect.Value)

            type MapIndex

            type MapIndex struct {
            	// contains filtered or unexported fields
            }

              MapIndex is an index operation on a map at some index Key.

              func (MapIndex) Key

              func (mi MapIndex) Key() reflect.Value

                Key is the value of the map key.

                func (MapIndex) String

                func (mi MapIndex) String() string

                func (MapIndex) Type

                func (mi MapIndex) Type() reflect.Type

                func (MapIndex) Values

                func (mi MapIndex) Values() (vx, vy reflect.Value)

                type Option

                type Option interface {
                	// contains filtered or unexported methods
                }

                  Option configures for specific behavior of Equal and Diff. In particular, the fundamental Option functions (Ignore, Transformer, and Comparer), configure how equality is determined.

                  The fundamental options may be composed with filters (FilterPath and FilterValues) to control the scope over which they are applied.

                  The cmp/cmpopts package provides helper functions for creating options that may be used with Equal and Diff.

                  Example (ApproximateFloats)

                    Approximate equality for floats can be handled by defining a custom comparer on floats that determines two values to be equal if they are within some range of each other.

                    This example is for demonstrative purposes; use cmpopts.EquateApprox instead.

                    Output:
                    
                    true
                    false
                    false
                    
                    Example (AvoidEqualMethod)

                      If the Equal method defined on a type is not suitable, the type can be dynamically transformed to be stripped of the Equal method (or any method for that matter).

                      Output:
                      
                      true
                      false
                      
                      Example (EqualEmpty)

                        Sometimes, an empty map or slice is considered equal to an allocated one of zero length.

                        This example is for demonstrative purposes; use cmpopts.EquateEmpty instead.

                        Output:
                        
                        true
                        false
                        false
                        
                        Example (EqualNaNs)

                          Normal floating-point arithmetic defines == to be false when comparing NaN with itself. In certain cases, this is not the desired property.

                          This example is for demonstrative purposes; use cmpopts.EquateNaNs instead.

                          Output:
                          
                          true
                          false
                          false
                          
                          Example (EqualNaNsAndApproximateFloats)

                            To have floating-point comparisons combine both properties of NaN being equal to itself and also approximate equality of values, filters are needed to restrict the scope of the comparison so that they are composable.

                            This example is for demonstrative purposes; use cmpopts.EquateNaNs and cmpopts.EquateApprox instead.

                            Output:
                            
                            true
                            false
                            false
                            
                            Example (SortedSlice)

                              Two slices may be considered equal if they have the same elements, regardless of the order that they appear in. Transformations can be used to sort the slice.

                              This example is for demonstrative purposes; use cmpopts.SortSlices instead.

                              Output:
                              
                              true
                              false
                              false
                              
                              Example (TransformComplex)

                                The complex numbers complex64 and complex128 can really just be decomposed into a pair of float32 or float64 values. It would be convenient to be able define only a single comparator on float64 and have float32, complex64, and complex128 all be able to use that comparator. Transformations can be used to handle this.

                                Output:
                                
                                true
                                false
                                false
                                

                                func AllowUnexported

                                func AllowUnexported(types ...interface{}) Option

                                  AllowUnexported returns an Options that allows Equal to forcibly introspect unexported fields of the specified struct types.

                                  See Exporter for the proper use of this option.

                                  func Comparer

                                  func Comparer(f interface{}) Option

                                    Comparer returns an Option that determines whether two values are equal to each other.

                                    The comparer f must be a function "func(T, T) bool" and is implicitly filtered to input values assignable to T. If T is an interface, it is possible that f is called with two values of different concrete types that both implement T.

                                    The equality function must be:

                                    • Symmetric: equal(x, y) == equal(y, x)
                                    • Deterministic: equal(x, y) == equal(x, y)
                                    • Pure: equal(x, y) does not modify x or y
                                    

                                    func Exporter

                                    func Exporter(f func(reflect.Type) bool) Option

                                      Exporter returns an Option that specifies whether Equal is allowed to introspect into the unexported fields of certain struct types.

                                      Users of this option must understand that comparing on unexported fields from external packages is not safe since changes in the internal implementation of some external package may cause the result of Equal to unexpectedly change. However, it may be valid to use this option on types defined in an internal package where the semantic meaning of an unexported field is in the control of the user.

                                      In many cases, a custom Comparer should be used instead that defines equality as a function of the public API of a type rather than the underlying unexported implementation.

                                      For example, the reflect.Type documentation defines equality to be determined by the == operator on the interface (essentially performing a shallow pointer comparison) and most attempts to compare *regexp.Regexp types are interested in only checking that the regular expression strings are equal. Both of these are accomplished using Comparers:

                                      Comparer(func(x, y reflect.Type) bool { return x == y })
                                      Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
                                      

                                      In other cases, the cmpopts.IgnoreUnexported option can be used to ignore all unexported fields on specified struct types.

                                      func FilterPath

                                      func FilterPath(f func(Path) bool, opt Option) Option

                                        FilterPath returns a new Option where opt is only evaluated if filter f returns true for the current Path in the value tree.

                                        This filter is called even if a slice element or map entry is missing and provides an opportunity to ignore such cases. The filter function must be symmetric such that the filter result is identical regardless of whether the missing value is from x or y.

                                        The option passed in may be an Ignore, Transformer, Comparer, Options, or a previously filtered Option.

                                        func FilterValues

                                        func FilterValues(f interface{}, opt Option) Option

                                          FilterValues returns a new Option where opt is only evaluated if filter f, which is a function of the form "func(T, T) bool", returns true for the current pair of values being compared. If either value is invalid or the type of the values is not assignable to T, then this filter implicitly returns false.

                                          The filter function must be symmetric (i.e., agnostic to the order of the inputs) and deterministic (i.e., produces the same result when given the same inputs). If T is an interface, it is possible that f is called with two values with different concrete types that both implement T.

                                          The option passed in may be an Ignore, Transformer, Comparer, Options, or a previously filtered Option.

                                          func Ignore

                                          func Ignore() Option

                                            Ignore is an Option that causes all comparisons to be ignored. This value is intended to be combined with FilterPath or FilterValues. It is an error to pass an unfiltered Ignore option to Equal.

                                            func Reporter

                                            func Reporter(r interface {
                                            	// PushStep is called when a tree-traversal operation is performed.
                                            	// The PathStep itself is only valid until the step is popped.
                                            	// The PathStep.Values are valid for the duration of the entire traversal
                                            	// and must not be mutated.
                                            	//
                                            	// Equal always calls PushStep at the start to provide an operation-less
                                            	// PathStep used to report the root values.
                                            	//
                                            	// Within a slice, the exact set of inserted, removed, or modified elements
                                            	// is unspecified and may change in future implementations.
                                            	// The entries of a map are iterated through in an unspecified order.
                                            	PushStep(PathStep)
                                            
                                            	// Report is called exactly once on leaf nodes to report whether the
                                            	// comparison identified the node as equal, unequal, or ignored.
                                            	// A leaf node is one that is immediately preceded by and followed by
                                            	// a pair of PushStep and PopStep calls.
                                            	Report(Result)
                                            
                                            	// PopStep ascends back up the value tree.
                                            	// There is always a matching pop call for every push call.
                                            	PopStep()
                                            }) Option

                                              Reporter is an Option that can be passed to Equal. When Equal traverses the value trees, it calls PushStep as it descends into each node in the tree and PopStep as it ascend out of the node. The leaves of the tree are either compared (determined to be equal or not equal) or ignored and reported as such by calling the Report method.

                                              Example
                                              Output:
                                              
                                              {cmp_test.Gateway}.IPAddress:
                                              	-: 192.168.0.1
                                              	+: 192.168.0.2
                                              
                                              {cmp_test.Gateway}.Clients[4].IPAddress:
                                              	-: 192.168.0.219
                                              	+: 192.168.0.221
                                              
                                              {cmp_test.Gateway}.Clients[5->?]:
                                              	-: {Hostname:americano IPAddress:192.168.0.188 LastSeen:2009-11-10 23:03:05 +0000 UTC}
                                              	+: <invalid reflect.Value>
                                              

                                              func Transformer

                                              func Transformer(name string, f interface{}) Option

                                                Transformer returns an Option that applies a transformation function that converts values of a certain type into that of another.

                                                The transformer f must be a function "func(T) R" that converts values of type T to those of type R and is implicitly filtered to input values assignable to T. The transformer must not mutate T in any way.

                                                To help prevent some cases of infinite recursive cycles applying the same transform to the output of itself (e.g., in the case where the input and output types are the same), an implicit filter is added such that a transformer is applicable only if that exact transformer is not already in the tail of the Path since the last non-Transform step. For situations where the implicit filter is still insufficient, consider using cmpopts.AcyclicTransformer, which adds a filter to prevent the transformer from being recursively applied upon itself.

                                                The name is a user provided label that is used as the Transform.Name in the transformation PathStep (and eventually shown in the Diff output). The name must be a valid identifier or qualified identifier in Go syntax. If empty, an arbitrary name is used.

                                                type Options

                                                type Options []Option

                                                  Options is a list of Option values that also satisfies the Option interface. Helper comparison packages may return an Options value when packing multiple Option values into a single Option. When this package processes an Options, it will be implicitly expanded into a flat list.

                                                  Applying a filter on an Options is equivalent to applying that same filter on all individual options held within.

                                                  func (Options) String

                                                  func (opts Options) String() string

                                                  type Path

                                                  type Path []PathStep

                                                    Path is a list of PathSteps describing the sequence of operations to get from some root type to the current position in the value tree. The first Path element is always an operation-less PathStep that exists simply to identify the initial type.

                                                    When traversing structs with embedded structs, the embedded struct will always be accessed as a field before traversing the fields of the embedded struct themselves. That is, an exported field from the embedded struct will never be accessed directly from the parent struct.

                                                    func (Path) GoString

                                                    func (pa Path) GoString() string

                                                      GoString returns the path to a specific node using Go syntax.

                                                      For example:

                                                      (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
                                                      

                                                      func (Path) Index

                                                      func (pa Path) Index(i int) PathStep

                                                        Index returns the ith step in the Path and supports negative indexing. A negative index starts counting from the tail of the Path such that -1 refers to the last step, -2 refers to the second-to-last step, and so on. If index is invalid, this returns a non-nil PathStep that reports a nil Type.

                                                        func (Path) Last

                                                        func (pa Path) Last() PathStep

                                                          Last returns the last PathStep in the Path. If the path is empty, this returns a non-nil PathStep that reports a nil Type.

                                                          func (Path) String

                                                          func (pa Path) String() string

                                                            String returns the simplified path to a node. The simplified path only contains struct field accesses.

                                                            For example:

                                                            MyMap.MySlices.MyField
                                                            

                                                            type PathStep

                                                            type PathStep interface {
                                                            	String() string
                                                            
                                                            	// Type is the resulting type after performing the path step.
                                                            	Type() reflect.Type
                                                            
                                                            	// Values is the resulting values after performing the path step.
                                                            	// The type of each valid value is guaranteed to be identical to Type.
                                                            	//
                                                            	// In some cases, one or both may be invalid or have restrictions:
                                                            	//	• For StructField, both are not interface-able if the current field
                                                            	//	is unexported and the struct type is not explicitly permitted by
                                                            	//	an Exporter to traverse unexported fields.
                                                            	//	• For SliceIndex, one may be invalid if an element is missing from
                                                            	//	either the x or y slice.
                                                            	//	• For MapIndex, one may be invalid if an entry is missing from
                                                            	//	either the x or y map.
                                                            	//
                                                            	// The provided values must not be mutated.
                                                            	Values() (vx, vy reflect.Value)
                                                            }

                                                              PathStep is a union-type for specific operations to traverse a value's tree structure. Users of this package never need to implement these types as values of this type will be returned by this package.

                                                              Implementations of this interface are StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.

                                                              type Result

                                                              type Result struct {
                                                              	// contains filtered or unexported fields
                                                              }

                                                                Result represents the comparison result for a single node and is provided by cmp when calling Result (see Reporter).

                                                                func (Result) ByCycle

                                                                func (r Result) ByCycle() bool

                                                                  ByCycle reports whether a reference cycle was detected.

                                                                  func (Result) ByFunc

                                                                  func (r Result) ByFunc() bool

                                                                    ByFunc reports whether a Comparer function determined equality.

                                                                    func (Result) ByIgnore

                                                                    func (r Result) ByIgnore() bool

                                                                      ByIgnore reports whether the node is equal because it was ignored. This never reports true if Equal reports false.

                                                                      func (Result) ByMethod

                                                                      func (r Result) ByMethod() bool

                                                                        ByMethod reports whether the Equal method determined equality.

                                                                        func (Result) Equal

                                                                        func (r Result) Equal() bool

                                                                          Equal reports whether the node was determined to be equal or not. As a special case, ignored nodes are considered equal.

                                                                          type SliceIndex

                                                                          type SliceIndex struct {
                                                                          	// contains filtered or unexported fields
                                                                          }

                                                                            SliceIndex is an index operation on a slice or array at some index Key.

                                                                            func (SliceIndex) Key

                                                                            func (si SliceIndex) Key() int

                                                                              Key is the index key; it may return -1 if in a split state

                                                                              func (SliceIndex) SplitKeys

                                                                              func (si SliceIndex) SplitKeys() (ix, iy int)

                                                                                SplitKeys are the indexes for indexing into slices in the x and y values, respectively. These indexes may differ due to the insertion or removal of an element in one of the slices, causing all of the indexes to be shifted. If an index is -1, then that indicates that the element does not exist in the associated slice.

                                                                                Key is guaranteed to return -1 if and only if the indexes returned by SplitKeys are not the same. SplitKeys will never return -1 for both indexes.

                                                                                func (SliceIndex) String

                                                                                func (si SliceIndex) String() string

                                                                                func (SliceIndex) Type

                                                                                func (si SliceIndex) Type() reflect.Type

                                                                                func (SliceIndex) Values

                                                                                func (si SliceIndex) Values() (vx, vy reflect.Value)

                                                                                type StructField

                                                                                type StructField struct {
                                                                                	// contains filtered or unexported fields
                                                                                }

                                                                                  StructField represents a struct field access on a field called Name.

                                                                                  func (StructField) Index

                                                                                  func (sf StructField) Index() int

                                                                                    Index is the index of the field in the parent struct type. See reflect.Type.Field.

                                                                                    func (StructField) Name

                                                                                    func (sf StructField) Name() string

                                                                                      Name is the field name.

                                                                                      func (StructField) String

                                                                                      func (sf StructField) String() string

                                                                                      func (StructField) Type

                                                                                      func (sf StructField) Type() reflect.Type

                                                                                      func (StructField) Values

                                                                                      func (sf StructField) Values() (vx, vy reflect.Value)

                                                                                      type Transform

                                                                                      type Transform struct {
                                                                                      	// contains filtered or unexported fields
                                                                                      }

                                                                                        Transform is a transformation from the parent type to the current type.

                                                                                        func (Transform) Func

                                                                                        func (tf Transform) Func() reflect.Value

                                                                                          Func is the function pointer to the transformer function.

                                                                                          func (Transform) Name

                                                                                          func (tf Transform) Name() string

                                                                                            Name is the name of the Transformer.

                                                                                            func (Transform) Option

                                                                                            func (tf Transform) Option() Option

                                                                                              Option returns the originally constructed Transformer option. The == operator can be used to detect the exact option used.

                                                                                              func (Transform) String

                                                                                              func (tf Transform) String() string

                                                                                              func (Transform) Type

                                                                                              func (tf Transform) Type() reflect.Type

                                                                                              func (Transform) Values

                                                                                              func (tf Transform) Values() (vx, vy reflect.Value)

                                                                                              type TypeAssertion

                                                                                              type TypeAssertion struct {
                                                                                              	// contains filtered or unexported fields
                                                                                              }

                                                                                                TypeAssertion represents a type assertion on an interface.

                                                                                                func (TypeAssertion) String

                                                                                                func (ta TypeAssertion) String() string

                                                                                                func (TypeAssertion) Type

                                                                                                func (ta TypeAssertion) Type() reflect.Type

                                                                                                func (TypeAssertion) Values

                                                                                                func (ta TypeAssertion) Values() (vx, vy reflect.Value)

                                                                                                Directories

                                                                                                Path Synopsis
                                                                                                Package cmpopts provides common options for the cmp package.
                                                                                                Package cmpopts provides common options for the cmp package.
                                                                                                internal
                                                                                                diff
                                                                                                Package diff implements an algorithm for producing edit-scripts.
                                                                                                Package diff implements an algorithm for producing edit-scripts.
                                                                                                function
                                                                                                Package function provides functionality for identifying function types.
                                                                                                Package function provides functionality for identifying function types.
                                                                                                teststructs/foo1
                                                                                                Package foo is deliberately named differently than the parent directory.
                                                                                                Package foo is deliberately named differently than the parent directory.
                                                                                                teststructs/foo2
                                                                                                Package foo is deliberately named differently than the parent directory.
                                                                                                Package foo is deliberately named differently than the parent directory.