Last active
April 25, 2018 18:52
-
-
Save ColinSullivan1/0b182ff633eadb8fe67d9b1bfb61f007 to your computer and use it in GitHub Desktop.
Test to get an interface using a "factory" name.
This file contains hidden or 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" | |
) | |
// 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