Skip to content

Instantly share code, notes, and snippets.

@ColinSullivan1
Last active April 25, 2018 18:52
Show Gist options
  • Save ColinSullivan1/0b182ff633eadb8fe67d9b1bfb61f007 to your computer and use it in GitHub Desktop.
Save ColinSullivan1/0b182ff633eadb8fe67d9b1bfb61f007 to your computer and use it in GitHub Desktop.
Test to get an interface using a "factory" name.
package main
import (
"fmt"
"reflect"
)
// Store is our fake Store
type Store interface {
FakeStoreInterfaceFunc()
}
// MyLittleStore is our store interface implementation
type MyLittleStore struct{}
// FakeStoreInterfaceFunc - placeholder
func (*MyLittleStore) FakeStoreInterfaceFunc() {
fmt.Printf("Cool, it works.\n")
}
// ExtendedStore name is static to generate store
type ExtendedStore struct{}
// NewMyLittleStore returns a store
func (*ExtendedStore) NewMyLittleStore() Store {
return &MyLittleStore{}
}
// CreateStoreByName creates a store by name
func CreateStoreByName() {
// we need a struct to call by name
extStore := ExtendedStore{}
// look up the function
createFunc := reflect.ValueOf(&extStore).MethodByName("NewMyLittleStore")
// Call creation function
values := createFunc.Call([]reflect.Value{})
// get the store from the values
var s Store
s = values[0].Interface().(Store)
// test the interface
s.FakeStoreInterfaceFunc()
}
func main() {
CreateStoreByName()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment