Skip to content

Instantly share code, notes, and snippets.

@kai5263499
Created September 5, 2017 03:54
Show Gist options
  • Save kai5263499/35a83122def7edc7a1830b7073f8eaf0 to your computer and use it in GitHub Desktop.
Save kai5263499/35a83122def7edc7a1830b7073f8eaf0 to your computer and use it in GitHub Desktop.
Example of checking whether a struct fulfills an interface dynamically at runtime
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