|
| 1 | +# Comparing and Converting Structs |
| 2 | +// Whether or not a struct is comparable depends on the struct’s fields. Structs that |
| 3 | +// are entirely composed out of comparable types are comparable; those with slice |
| 4 | +// or map fields are not (as we will see in later chapters, function and channel fields |
| 5 | +// also prevent a struct from being comparable). |
| 6 | +// |
| 7 | +// Unlike Python or Ruby, there’s no magic method that can be overridden to |
| 8 | +// redefine equality and make == and != work for incomparable structs. You can, |
| 9 | +// of course, write your own function that you use to compare structs. |
| 10 | +// |
| 11 | +// Just like Go+ doesn’t allow comparisons between variables of different primitive |
| 12 | +// types, Go+ doesn’t allow comparisons between variables that represent structs of |
| 13 | +// different types. Go+ does allow you to perform a type conversion from one struct |
| 14 | +// type to another if the fields of both structs have the same names, order, and |
| 15 | +// types. Let’s see what this means. Given this struct: |
| 16 | + |
| 17 | +type firstPerson struct { |
| 18 | + name string |
| 19 | + age int |
| 20 | +} |
| 21 | + |
| 22 | +type secondPerson struct { |
| 23 | + name string |
| 24 | + age int |
| 25 | +} |
| 26 | + |
| 27 | +type thirdPerson struct { |
| 28 | + age int |
| 29 | + name string |
| 30 | +} |
| 31 | + |
| 32 | +first := firstPerson{name: "Bob", age: 22} |
| 33 | +second := secondPerson{name: "Joe", age: 23} |
| 34 | +third := thirdPerson{name: "Sars", age: 24} |
| 35 | +first = firstPerson(second) |
| 36 | +println first |
| 37 | +first = firstPerson(third) |
| 38 | +println first |
| 39 | + |
| 40 | +// We can use a type conversion to convert an instance of secondPerson to |
| 41 | +// firstPerson, but we can’t convert an instance of thirdPerson to firstPerson, because the |
| 42 | +// fields are in a different order. |
| 43 | +// But we can’t use == to compare an instance of firstPerson and an instance of secondPerson or thirdPerson, |
| 44 | +// because they are different types. |
0 commit comments