MCPcopy
hub / github.com/google/go-cmp / ExampleOption_transformComplex

Function ExampleOption_transformComplex

cmp/example_test.go:264–304  ·  cmp/example_test.go::ExampleOption_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 use

()

Source from the content-addressed store, hash-verified

262// complex128 all be able to use that comparator. Transformations can be used
263// to handle this.
264func ExampleOption_transformComplex() {
265 opts := []cmp.Option{
266 // This transformer decomposes complex128 into a pair of float64s.
267 cmp.Transformer("T1", func(in complex128) (out struct{ Real, Imag float64 }) {
268 out.Real, out.Imag = real(in), imag(in)
269 return out
270 }),
271 // This transformer converts complex64 to complex128 to allow the
272 // above transform to take effect.
273 cmp.Transformer("T2", func(in complex64) complex128 {
274 return complex128(in)
275 }),
276 // This transformer converts float32 to float64.
277 cmp.Transformer("T3", func(in float32) float64 {
278 return float64(in)
279 }),
280 // This equality function compares float64s as rounded integers.
281 cmp.Comparer(func(x, y float64) bool {
282 return roundF64(x) == roundF64(y)
283 }),
284 }
285
286 x := []interface{}{
287 complex128(3.0), complex64(5.1 + 2.9i), float32(-1.2), float64(12.3),
288 }
289 y := []interface{}{
290 complex128(3.1), complex64(4.9 + 3.1i), float32(-1.3), float64(11.7),
291 }
292 z := []interface{}{
293 complex128(3.8), complex64(4.9 + 3.1i), float32(-1.3), float64(11.7),
294 }
295
296 fmt.Println(cmp.Equal(x, y, opts...))
297 fmt.Println(cmp.Equal(y, z, opts...))
298 fmt.Println(cmp.Equal(z, x, opts...))
299
300 // Output:
301 // true
302 // false
303 // false
304}
305
306type (
307 Gateway struct {

Callers

nothing calls this directly

Calls 4

TransformerFunction · 0.92
ComparerFunction · 0.92
EqualFunction · 0.92
roundF64Function · 0.85

Tested by

no test coverage detected