Skip to content

Instantly share code, notes, and snippets.

@sgnn7
Last active June 18, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgnn7/a49e76c1a2f3e4805c95e72c60e020e1 to your computer and use it in GitHub Desktop.
Save sgnn7/a49e76c1a2f3e4805c95e72c60e020e1 to your computer and use it in GitHub Desktop.
Instantiate an abstract Golang struct dynamically with parameters
package main
// Author: Srdjan Grubor
// License: Apache-2.0
import (
"fmt"
)
// Interface common for all classes
type MainInterface interface {
GetId() string
}
// First type of object
type FirstType struct {
Id string
}
func (ft *FirstType) GetId() string {
return ft.Id
}
// FirstType factory
func InitializeFirstType(id string) MainInterface {
return &FirstType{Id: id}
}
// Second type of object
type SecondType struct {
Id string
}
func (st *SecondType) GetId() string {
return st.Id
}
// SecondType factory
func InitializeSecondType(id string) MainInterface {
return &SecondType{Id: id}
}
func main() {
// Map of strings to factories
classes := map[string]func(string) MainInterface{
"first": InitializeFirstType,
"second": InitializeSecondType,
}
// Create a new FirstType object with value of 10 using the factory
newObject := classes["first"]("10")
// Show that we have the object correctly created
fmt.Printf("%v\n", newObject.GetId())
// Create a new SecondType object with value of 20 using the factory
newObject2 := classes["second"]("20")
// Show that we have the object correctly created
fmt.Printf("%v\n", newObject2.GetId())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment