是否有更惯用的方法来根据输入创建特定类型的变量?

这个游乐场链接中,我创建了我的代码的一个人为版本,我在其中创建了一个基于输入字符串的 X 类型的变量。该变量将是少数类型之一并实现一个接口。

该代码当前编译并提供了正确的结果,但是它给我留下了相当冗长的印象,我正在尝试寻找是否有一种速记方法来实现我正在实现的结果。该示例有 3 种实现接口(动物)的类型(狗、猫和鸟),但是我的实际代码在此 switch 语句中将有多达 40 种类型。

我使用这段代码的原因是当从 DBMS 中检索结果时,我试图使用一种通用的加载方法,当与sqlx结合使用时,它会根据输入字符串将数据库表加载到正确的结构中。我可以完全控制应用程序,并且可以根据需要将输入字符串更改为另一种类型。

来自游乐场链接的代码:

package main


import (

    "fmt"

)


type animal interface {

    call() string

}


type dog struct {

}


func (d *dog) call() string {

    return "Woof!"

}


type cat struct {

}


func (c *cat) call() string {

    return "Meow!"

}


type bird struct {

}


func (c *bird) call() string {

    return "Chirp!"

}


func main() {

    var animal animal

    animalType := "dog"

    switch animalType{

    case "dog":

        animal = new(dog)

    case "cat":

        animal = new(cat)

    case "bird":

        animal = new(bird)


慕哥6287543
浏览 65回答 1
1回答

米琪卡哇伊

您可以创建一个从“字符串”到“返回动物的函数”的哈希图,但设置它会比 switch 语句更冗长。像这样的(未测试)type AnimalCtor func() animalvar animalMap map[string]AnimalCtor.....func init() {    animalMap["dog"] = func() animal { return &dog{} }    animalMap["cat"] = func() animal { return &cat{} }    animalMap["bird"] = func() animal { return &bird{} }    .....}func createAnimalFromString(input string) animal {    ctor, ok := animalMap[input]    if ok {        return ctor()    } else {        return nil    }}但它比 switch 语句冗长得多,并且模糊了原本应该明确和清楚的内容。
打开App,查看更多内容
随时随地看视频慕课网APP