interface{}var w io.Writer = os.Stdout
f := w.(*os.File) // success
c := w.(*bytes.Buffer) // failure since the interface holds a *os.File not a *bytes.Buffer
c, ok := w.(*bytes.Buffer)
fmt and jsonfunc Println(args ...interface{}) {
// ...
for arg := range args {
switch a := arg.(type) {
case string: // concrete type
// do something with the string
case Stringer: // interface
// call the String() method on the interface to get the string representation
}
}
}
a takes on a value of the type it is, and when the case matches, a will have that corresponding type, meaning we can do things like call the methods on that Stringer interface==reflect.DeepEqual to do a reflection based equals that will look into slices and other normally non-comparable structures to check for equalitywant := struct{
someSlice := []int{1,2,3}
}
got := someFunction()
if !reflect.DeepEqual(got, want) {
fmt.Println("failed equality check")
}