Created
September 5, 2017 03:54
-
-
Save kai5263499/35a83122def7edc7a1830b7073f8eaf0 to your computer and use it in GitHub Desktop.
Example of checking whether a struct fulfills an interface dynamically at runtime
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
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type A interface { | |
Set(string) error | |
} | |
type B interface { | |
Get() string | |
} | |
type C struct { | |
hello string | |
} | |
func (c *C) Set(s string) error { | |
return nil | |
} | |
func main() { | |
c := &C{ | |
hello: "world", | |
} | |
// Force interface check at compile type | |
// C implements A | |
var _ A = (*C)(nil) | |
var ok bool | |
// Compile type check with reflection | |
dest := reflect.ValueOf(c) | |
_, ok = dest.Interface().(A) | |
fmt.Printf("c implements A - %v\n", ok) | |
_, ok = dest.Interface().(B) | |
fmt.Printf("c implements B - %v\n", ok) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment