Last active
February 2, 2020 18:29
-
-
Save dcormier/38eab84e84362826079d84e37017f059 to your computer and use it in GitHub Desktop.
Golang reflect.DeepEqual() example; does it do what you mean?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Runable: https://play.golang.org/p/-bkg2k6ymCR | |
// | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
"time" | |
) | |
type thing struct { | |
a string | |
b *string | |
c time.Time | |
d *time.Time | |
} | |
func main() { | |
one := &thing{ | |
a: "a", | |
b: new(string), | |
c: time.Now(), | |
d: new(time.Time), | |
} | |
*one.b = "b" | |
*one.d = one.c.Add(4) | |
two := &thing{ | |
a: one.a, | |
b: new(string), | |
c: one.c, | |
d: new(time.Time), | |
} | |
*two.b = *one.b | |
*two.d = *one.d | |
fmt.Println("Different pointers, but the final values are all the same.") | |
fmt.Printf("one: %#v\n", one) | |
fmt.Printf("two: %#v\n", two) | |
fmt.Printf("Equal? %t\n", one == two) | |
fmt.Printf("Equal values? %t\n", *one == *two) | |
fmt.Printf("Deep equal? %t\n\n", reflect.DeepEqual(one, two)) | |
// Pointer to zero-value != nil. | |
three := &thing{} | |
four := &thing{ | |
b: new(string), | |
d: new(time.Time), | |
} | |
fmt.Println("Pointer to zero-value != nil.") | |
fmt.Printf("three: %#v\n", three) | |
fmt.Printf("four: %#v\n", four) | |
fmt.Printf("Equal? %t\n", three == four) | |
fmt.Printf("Equal values? %t\n", *three == *four) | |
fmt.Printf("Deep equal? %t\n", reflect.DeepEqual(three, four)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment