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