1// Copyright 2017, The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// Package cmp determines equality of values. 6// 7// This package is intended to be a more powerful and safer alternative to 8// reflect.DeepEqual for comparing whether two values are semantically equal. 9// It is intended to only be used in tests, as performance is not a goal and 10// it may panic if it cannot compare the values. Its propensity towards 11// panicking means that its unsuitable for production environments where a 12// spurious panic may be fatal. 13// 14// The primary features of cmp are: 15// 16// • When the default behavior of equality does not suit the needs of the test, 17// custom equality functions can override the equality operation. 18// For example, an equality function may report floats as equal so long as they 19// are within some tolerance of each other. 20// 21// • Types that have an Equal method may use that method to determine equality. 22// This allows package authors to determine the equality operation for the types 23// that they define. 24// 25// • If no custom equality functions are used and no Equal method is defined, 26// equality is determined by recursively comparing the primitive kinds on both 27// values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported 28// fields are not compared by default; they result in panics unless suppressed 29// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly 30// compared using the Exporter option. 31package cmp 32 33import ( 34 "fmt" 35 "reflect" 36 "strings" 37 38 "github.com/google/go-cmp/cmp/internal/diff" 39 "github.com/google/go-cmp/cmp/internal/function" 40 "github.com/google/go-cmp/cmp/internal/value" 41) 42 43// Equal reports whether x and y are equal by recursively applying the 44// following rules in the given order to x and y and all of their sub-values: 45// 46// • Let S be the set of all Ignore, Transformer, and Comparer options that 47// remain after applying all path filters, value filters, and type filters. 48// If at least one Ignore exists in S, then the comparison is ignored. 49// If the number of Transformer and Comparer options in S is greater than one, 50// then Equal panics because it is ambiguous which option to use. 51// If S contains a single Transformer, then use that to transform the current 52// values and recursively call Equal on the output values. 53// If S contains a single Comparer, then use that to compare the current values. 54// Otherwise, evaluation proceeds to the next rule. 55// 56// • If the values have an Equal method of the form "(T) Equal(T) bool" or 57// "(T) Equal(I) bool" where T is assignable to I, then use the result of 58// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and 59// evaluation proceeds to the next rule. 60// 61// • Lastly, try to compare x and y based on their basic kinds. 62// Simple kinds like booleans, integers, floats, complex numbers, strings, and 63// channels are compared using the equivalent of the == operator in Go. 64// Functions are only equal if they are both nil, otherwise they are unequal. 65// 66// Structs are equal if recursively calling Equal on all fields report equal. 67// If a struct contains unexported fields, Equal panics unless an Ignore option 68// (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option 69// explicitly permits comparing the unexported field. 70// 71// Slices are equal if they are both nil or both non-nil, where recursively 72// calling Equal on all non-ignored slice or array elements report equal. 73// Empty non-nil slices and nil slices are not equal; to equate empty slices, 74// consider using cmpopts.EquateEmpty. 75// 76// Maps are equal if they are both nil or both non-nil, where recursively 77// calling Equal on all non-ignored map entries report equal. 78// Map keys are equal according to the == operator. 79// To use custom comparisons for map keys, consider using cmpopts.SortMaps. 80// Empty non-nil maps and nil maps are not equal; to equate empty maps, 81// consider using cmpopts.EquateEmpty. 82// 83// Pointers and interfaces are equal if they are both nil or both non-nil, 84// where they have the same underlying concrete type and recursively 85// calling Equal on the underlying values reports equal. 86// 87// Before recursing into a pointer, slice element, or map, the current path 88// is checked to detect whether the address has already been visited. 89// If there is a cycle, then the pointed at values are considered equal 90// only if both addresses were previously visited in the same path step. 91func Equal(x, y interface{}, opts ...Option) bool { 92 s := newState(opts) 93 s.compareAny(rootStep(x, y)) 94 return s.result.Equal() 95} 96 97// Diff returns a human-readable report of the differences between two values: 98// y - x. It returns an empty string if and only if Equal returns true for the 99// same input values and options. 100// 101// The output is displayed as a literal in pseudo-Go syntax. 102// At the start of each line, a "-" prefix indicates an element removed from x, 103// a "+" prefix to indicates an element added from y, and the lack of a prefix 104// indicates an element common to both x and y. If possible, the output 105// uses fmt.Stringer.String or error.Error methods to produce more humanly 106// readable outputs. In such cases, the string is prefixed with either an 107// 's' or 'e' character, respectively, to indicate that the method was called. 108// 109// Do not depend on this output being stable. If you need the ability to 110// programmatically interpret the difference, consider using a custom Reporter. 111func Diff(x, y interface{}, opts ...Option) string { 112 s := newState(opts) 113 114 // Optimization: If there are no other reporters, we can optimize for the 115 // common case where the result is equal (and thus no reported difference). 116 // This avoids the expensive construction of a difference tree. 117 if len(s.reporters) == 0 { 118 s.compareAny(rootStep(x, y)) 119 if s.result.Equal() { 120 return "" 121 } 122 s.result = diff.Result{} // Reset results 123 } 124 125 r := new(defaultReporter) 126 s.reporters = append(s.reporters, reporter{r}) 127 s.compareAny(rootStep(x, y)) 128 d := r.String() 129 if (d == "") != s.result.Equal() { 130 panic("inconsistent difference and equality results") 131 } 132 return d 133} 134 135// rootStep constructs the first path step. If x and y have differing types, 136// then they are stored within an empty interface type. 137func rootStep(x, y interface{}) PathStep { 138 vx := reflect.ValueOf(x) 139 vy := reflect.ValueOf(y) 140 141 // If the inputs are different types, auto-wrap them in an empty interface 142 // so that they have the same parent type. 143 var t reflect.Type 144 if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { 145 t = reflect.TypeOf((*interface{})(nil)).Elem() 146 if vx.IsValid() { 147 vvx := reflect.New(t).Elem() 148 vvx.Set(vx) 149 vx = vvx 150 } 151 if vy.IsValid() { 152 vvy := reflect.New(t).Elem() 153 vvy.Set(vy) 154 vy = vvy 155 } 156 } else { 157 t = vx.Type() 158 } 159 160 return &pathStep{t, vx, vy} 161} 162 163type state struct { 164 // These fields represent the "comparison state". 165 // Calling statelessCompare must not result in observable changes to these. 166 result diff.Result // The current result of comparison 167 curPath Path // The current path in the value tree 168 curPtrs pointerPath // The current set of visited pointers 169 reporters []reporter // Optional reporters 170 171 // recChecker checks for infinite cycles applying the same set of 172 // transformers upon the output of itself. 173 recChecker recChecker 174 175 // dynChecker triggers pseudo-random checks for option correctness. 176 // It is safe for statelessCompare to mutate this value. 177 dynChecker dynChecker 178 179 // These fields, once set by processOption, will not change. 180 exporters []exporter // List of exporters for structs with unexported fields 181 opts Options // List of all fundamental and filter options 182} 183 184func newState(opts []Option) *state { 185 // Always ensure a validator option exists to validate the inputs. 186 s := &state{opts: Options{validator{}}} 187 s.curPtrs.Init() 188 s.processOption(Options(opts)) 189 return s 190} 191 192func (s *state) processOption(opt Option) { 193 switch opt := opt.(type) { 194 case nil: 195 case Options: 196 for _, o := range opt { 197 s.processOption(o) 198 } 199 case coreOption: 200 type filtered interface { 201 isFiltered() bool 202 } 203 if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() { 204 panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt)) 205 } 206 s.opts = append(s.opts, opt) 207 case exporter: 208 s.exporters = append(s.exporters, opt) 209 case reporter: 210 s.reporters = append(s.reporters, opt) 211 default: 212 panic(fmt.Sprintf("unknown option %T", opt)) 213 } 214} 215 216// statelessCompare compares two values and returns the result. 217// This function is stateless in that it does not alter the current result, 218// or output to any registered reporters. 219func (s *state) statelessCompare(step PathStep) diff.Result { 220 // We do not save and restore curPath and curPtrs because all of the 221 // compareX methods should properly push and pop from them. 222 // It is an implementation bug if the contents of the paths differ from 223 // when calling this function to when returning from it. 224 225 oldResult, oldReporters := s.result, s.reporters 226 s.result = diff.Result{} // Reset result 227 s.reporters = nil // Remove reporters to avoid spurious printouts 228 s.compareAny(step) 229 res := s.result 230 s.result, s.reporters = oldResult, oldReporters 231 return res 232} 233 234func (s *state) compareAny(step PathStep) { 235 // Update the path stack. 236 s.curPath.push(step) 237 defer s.curPath.pop() 238 for _, r := range s.reporters { 239 r.PushStep(step) 240 defer r.PopStep() 241 } 242 s.recChecker.Check(s.curPath) 243 244 // Cycle-detection for slice elements (see NOTE in compareSlice). 245 t := step.Type() 246 vx, vy := step.Values() 247 if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() { 248 px, py := vx.Addr(), vy.Addr() 249 if eq, visited := s.curPtrs.Push(px, py); visited { 250 s.report(eq, reportByCycle) 251 return 252 } 253 defer s.curPtrs.Pop(px, py) 254 } 255 256 // Rule 1: Check whether an option applies on this node in the value tree. 257 if s.tryOptions(t, vx, vy) { 258 return 259 } 260 261 // Rule 2: Check whether the type has a valid Equal method. 262 if s.tryMethod(t, vx, vy) { 263 return 264 } 265 266 // Rule 3: Compare based on the underlying kind. 267 switch t.Kind() { 268 case reflect.Bool: 269 s.report(vx.Bool() == vy.Bool(), 0) 270 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 271 s.report(vx.Int() == vy.Int(), 0) 272 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 273 s.report(vx.Uint() == vy.Uint(), 0) 274 case reflect.Float32, reflect.Float64: 275 s.report(vx.Float() == vy.Float(), 0) 276 case reflect.Complex64, reflect.Complex128: 277 s.report(vx.Complex() == vy.Complex(), 0) 278 case reflect.String: 279 s.report(vx.String() == vy.String(), 0) 280 case reflect.Chan, reflect.UnsafePointer: 281 s.report(vx.Pointer() == vy.Pointer(), 0) 282 case reflect.Func: 283 s.report(vx.IsNil() && vy.IsNil(), 0) 284 case reflect.Struct: 285 s.compareStruct(t, vx, vy) 286 case reflect.Slice, reflect.Array: 287 s.compareSlice(t, vx, vy) 288 case reflect.Map: 289 s.compareMap(t, vx, vy) 290 case reflect.Ptr: 291 s.comparePtr(t, vx, vy) 292 case reflect.Interface: 293 s.compareInterface(t, vx, vy) 294 default: 295 panic(fmt.Sprintf("%v kind not handled", t.Kind())) 296 } 297} 298 299func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool { 300 // Evaluate all filters and apply the remaining options. 301 if opt := s.opts.filter(s, t, vx, vy); opt != nil { 302 opt.apply(s, vx, vy) 303 return true 304 } 305 return false 306} 307 308func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool { 309 // Check if this type even has an Equal method. 310 m, ok := t.MethodByName("Equal") 311 if !ok || !function.IsType(m.Type, function.EqualAssignable) { 312 return false 313 } 314 315 eq := s.callTTBFunc(m.Func, vx, vy) 316 s.report(eq, reportByMethod) 317 return true 318} 319 320func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value { 321 if !s.dynChecker.Next() { 322 return f.Call([]reflect.Value{v})[0] 323 } 324 325 // Run the function twice and ensure that we get the same results back. 326 // We run in goroutines so that the race detector (if enabled) can detect 327 // unsafe mutations to the input. 328 c := make(chan reflect.Value) 329 go detectRaces(c, f, v) 330 got := <-c 331 want := f.Call([]reflect.Value{v})[0] 332 if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() { 333 // To avoid false-positives with non-reflexive equality operations, 334 // we sanity check whether a value is equal to itself. 335 if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() { 336 return want 337 } 338 panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f))) 339 } 340 return want 341} 342 343func (s *state) callTTBFunc(f, x, y reflect.Value) bool { 344 if !s.dynChecker.Next() { 345 return f.Call([]reflect.Value{x, y})[0].Bool() 346 } 347 348 // Swapping the input arguments is sufficient to check that 349 // f is symmetric and deterministic. 350 // We run in goroutines so that the race detector (if enabled) can detect 351 // unsafe mutations to the input. 352 c := make(chan reflect.Value) 353 go detectRaces(c, f, y, x) 354 got := <-c 355 want := f.Call([]reflect.Value{x, y})[0].Bool() 356 if !got.IsValid() || got.Bool() != want { 357 panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f))) 358 } 359 return want 360} 361 362func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { 363 var ret reflect.Value 364 defer func() { 365 recover() // Ignore panics, let the other call to f panic instead 366 c <- ret 367 }() 368 ret = f.Call(vs)[0] 369} 370 371func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { 372 var addr bool 373 var vax, vay reflect.Value // Addressable versions of vx and vy 374 375 var mayForce, mayForceInit bool 376 step := StructField{&structField{}} 377 for i := 0; i < t.NumField(); i++ { 378 step.typ = t.Field(i).Type 379 step.vx = vx.Field(i) 380 step.vy = vy.Field(i) 381 step.name = t.Field(i).Name 382 step.idx = i 383 step.unexported = !isExported(step.name) 384 if step.unexported { 385 if step.name == "_" { 386 continue 387 } 388 // Defer checking of unexported fields until later to give an 389 // Ignore a chance to ignore the field. 390 if !vax.IsValid() || !vay.IsValid() { 391 // For retrieveUnexportedField to work, the parent struct must 392 // be addressable. Create a new copy of the values if 393 // necessary to make them addressable. 394 addr = vx.CanAddr() || vy.CanAddr() 395 vax = makeAddressable(vx) 396 vay = makeAddressable(vy) 397 } 398 if !mayForceInit { 399 for _, xf := range s.exporters { 400 mayForce = mayForce || xf(t) 401 } 402 mayForceInit = true 403 } 404 step.mayForce = mayForce 405 step.paddr = addr 406 step.pvx = vax 407 step.pvy = vay 408 step.field = t.Field(i) 409 } 410 s.compareAny(step) 411 } 412} 413 414func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) { 415 isSlice := t.Kind() == reflect.Slice 416 if isSlice && (vx.IsNil() || vy.IsNil()) { 417 s.report(vx.IsNil() && vy.IsNil(), 0) 418 return 419 } 420 421 // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer 422 // since slices represents a list of pointers, rather than a single pointer. 423 // The pointer checking logic must be handled on a per-element basis 424 // in compareAny. 425 // 426 // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting 427 // pointer P, a length N, and a capacity C. Supposing each slice element has 428 // a memory size of M, then the slice is equivalent to the list of pointers: 429 // [P+i*M for i in range(N)] 430 // 431 // For example, v[:0] and v[:1] are slices with the same starting pointer, 432 // but they are clearly different values. Using the slice pointer alone 433 // violates the assumption that equal pointers implies equal values. 434 435 step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}} 436 withIndexes := func(ix, iy int) SliceIndex { 437 if ix >= 0 { 438 step.vx, step.xkey = vx.Index(ix), ix 439 } else { 440 step.vx, step.xkey = reflect.Value{}, -1 441 } 442 if iy >= 0 { 443 step.vy, step.ykey = vy.Index(iy), iy 444 } else { 445 step.vy, step.ykey = reflect.Value{}, -1 446 } 447 return step 448 } 449 450 // Ignore options are able to ignore missing elements in a slice. 451 // However, detecting these reliably requires an optimal differencing 452 // algorithm, for which diff.Difference is not. 453 // 454 // Instead, we first iterate through both slices to detect which elements 455 // would be ignored if standing alone. The index of non-discarded elements 456 // are stored in a separate slice, which diffing is then performed on. 457 var indexesX, indexesY []int 458 var ignoredX, ignoredY []bool 459 for ix := 0; ix < vx.Len(); ix++ { 460 ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0 461 if !ignored { 462 indexesX = append(indexesX, ix) 463 } 464 ignoredX = append(ignoredX, ignored) 465 } 466 for iy := 0; iy < vy.Len(); iy++ { 467 ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0 468 if !ignored { 469 indexesY = append(indexesY, iy) 470 } 471 ignoredY = append(ignoredY, ignored) 472 } 473 474 // Compute an edit-script for slices vx and vy (excluding ignored elements). 475 edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result { 476 return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy])) 477 }) 478 479 // Replay the ignore-scripts and the edit-script. 480 var ix, iy int 481 for ix < vx.Len() || iy < vy.Len() { 482 var e diff.EditType 483 switch { 484 case ix < len(ignoredX) && ignoredX[ix]: 485 e = diff.UniqueX 486 case iy < len(ignoredY) && ignoredY[iy]: 487 e = diff.UniqueY 488 default: 489 e, edits = edits[0], edits[1:] 490 } 491 switch e { 492 case diff.UniqueX: 493 s.compareAny(withIndexes(ix, -1)) 494 ix++ 495 case diff.UniqueY: 496 s.compareAny(withIndexes(-1, iy)) 497 iy++ 498 default: 499 s.compareAny(withIndexes(ix, iy)) 500 ix++ 501 iy++ 502 } 503 } 504} 505 506func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) { 507 if vx.IsNil() || vy.IsNil() { 508 s.report(vx.IsNil() && vy.IsNil(), 0) 509 return 510 } 511 512 // Cycle-detection for maps. 513 if eq, visited := s.curPtrs.Push(vx, vy); visited { 514 s.report(eq, reportByCycle) 515 return 516 } 517 defer s.curPtrs.Pop(vx, vy) 518 519 // We combine and sort the two map keys so that we can perform the 520 // comparisons in a deterministic order. 521 step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}} 522 for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) { 523 step.vx = vx.MapIndex(k) 524 step.vy = vy.MapIndex(k) 525 step.key = k 526 if !step.vx.IsValid() && !step.vy.IsValid() { 527 // It is possible for both vx and vy to be invalid if the 528 // key contained a NaN value in it. 529 // 530 // Even with the ability to retrieve NaN keys in Go 1.12, 531 // there still isn't a sensible way to compare the values since 532 // a NaN key may map to multiple unordered values. 533 // The most reasonable way to compare NaNs would be to compare the 534 // set of values. However, this is impossible to do efficiently 535 // since set equality is provably an O(n^2) operation given only 536 // an Equal function. If we had a Less function or Hash function, 537 // this could be done in O(n*log(n)) or O(n), respectively. 538 // 539 // Rather than adding complex logic to deal with NaNs, make it 540 // the user's responsibility to compare such obscure maps. 541 const help = "consider providing a Comparer to compare the map" 542 panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help)) 543 } 544 s.compareAny(step) 545 } 546} 547 548func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) { 549 if vx.IsNil() || vy.IsNil() { 550 s.report(vx.IsNil() && vy.IsNil(), 0) 551 return 552 } 553 554 // Cycle-detection for pointers. 555 if eq, visited := s.curPtrs.Push(vx, vy); visited { 556 s.report(eq, reportByCycle) 557 return 558 } 559 defer s.curPtrs.Pop(vx, vy) 560 561 vx, vy = vx.Elem(), vy.Elem() 562 s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}}) 563} 564 565func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) { 566 if vx.IsNil() || vy.IsNil() { 567 s.report(vx.IsNil() && vy.IsNil(), 0) 568 return 569 } 570 vx, vy = vx.Elem(), vy.Elem() 571 if vx.Type() != vy.Type() { 572 s.report(false, 0) 573 return 574 } 575 s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}}) 576} 577 578func (s *state) report(eq bool, rf resultFlags) { 579 if rf&reportByIgnore == 0 { 580 if eq { 581 s.result.NumSame++ 582 rf |= reportEqual 583 } else { 584 s.result.NumDiff++ 585 rf |= reportUnequal 586 } 587 } 588 for _, r := range s.reporters { 589 r.Report(Result{flags: rf}) 590 } 591} 592 593// recChecker tracks the state needed to periodically perform checks that 594// user provided transformers are not stuck in an infinitely recursive cycle. 595type recChecker struct{ next int } 596 597// Check scans the Path for any recursive transformers and panics when any 598// recursive transformers are detected. Note that the presence of a 599// recursive Transformer does not necessarily imply an infinite cycle. 600// As such, this check only activates after some minimal number of path steps. 601func (rc *recChecker) Check(p Path) { 602 const minLen = 1 << 16 603 if rc.next == 0 { 604 rc.next = minLen 605 } 606 if len(p) < rc.next { 607 return 608 } 609 rc.next <<= 1 610 611 // Check whether the same transformer has appeared at least twice. 612 var ss []string 613 m := map[Option]int{} 614 for _, ps := range p { 615 if t, ok := ps.(Transform); ok { 616 t := t.Option() 617 if m[t] == 1 { // Transformer was used exactly once before 618 tf := t.(*transformer).fnc.Type() 619 ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) 620 } 621 m[t]++ 622 } 623 } 624 if len(ss) > 0 { 625 const warning = "recursive set of Transformers detected" 626 const help = "consider using cmpopts.AcyclicTransformer" 627 set := strings.Join(ss, "\n\t") 628 panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) 629 } 630} 631 632// dynChecker tracks the state needed to periodically perform checks that 633// user provided functions are symmetric and deterministic. 634// The zero value is safe for immediate use. 635type dynChecker struct{ curr, next int } 636 637// Next increments the state and reports whether a check should be performed. 638// 639// Checks occur every Nth function call, where N is a triangular number: 640// 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ... 641// See https://en.wikipedia.org/wiki/Triangular_number 642// 643// This sequence ensures that the cost of checks drops significantly as 644// the number of functions calls grows larger. 645func (dc *dynChecker) Next() bool { 646 ok := dc.curr == dc.next 647 if ok { 648 dc.curr = 0 649 dc.next++ 650 } 651 dc.curr++ 652 return ok 653} 654 655// makeAddressable returns a value that is always addressable. 656// It returns the input verbatim if it is already addressable, 657// otherwise it creates a new value and returns an addressable copy. 658func makeAddressable(v reflect.Value) reflect.Value { 659 if v.CanAddr() { 660 return v 661 } 662 vc := reflect.New(v.Type()).Elem() 663 vc.Set(v) 664 return vc 665} 666