latsha
latsha

Reputation: 1338

How to return instance of struct, idiomatic way

I've got function that returns struct instance depending on argument it takes

func Factory(s string) interface{} {
    if s == 'SomeType' {
        return SomeType{}
    } else if s == 'AnotherType' {
        return AnotherType{}
    }
}

this solution is good if I have a couple of structs to return but it's getting ugly if there are a lot of them, can I do it other way? Is there idiomatic way to do this?

Upvotes: 0

Views: 100

Answers (1)

Mad Wombat
Mad Wombat

Reputation: 15105

As the comment said, you can use a map for your types. Looks like this. The factory function will return an instance if the type exists or nil if it doesn't. package main

import (
    "fmt"
    "reflect"
)

type SomeType struct{ Something string }
type AnotherType struct{}
type YetAnotherType struct{}

var typemap = map[string]interface{}{
    "SomeType":       SomeType{ Something: "something" },
    "AnotherType":    AnotherType{},
    "YetAnotherType": YetAnotherType{},
}

func factory(s string) interface{} {
    t, ok := typemap[s]
    if ok {
        return reflect.ValueOf(t)
    }
    return nil
}

func main() {
    fmt.Printf("%#v\n", factory("SomeType"))
    fmt.Printf("%#v\n", factory("NoType"))
}

Playground link

Upvotes: 1

Related Questions