有没有一种更地道的方法来创建基于输入特定类型的变量?

问题描述 投票:0回答:1

this playground link我已经创建了我的代码在那里,我根据所输入的字符串制作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)
go
1个回答
2
投票

您可以从“串”一个HashMap来“的函数,返回的动物”,但设置,最多会比switch语句更详细。

事情是这样的(未测试)

type AnimalCtor func() animal

var 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语句更详细和掩盖什么原本应该是明确和清晰。

© www.soinside.com 2019 - 2024. All rights reserved.