登录
首页 >  Golang >  Go问答

构建一个函数映射来处理返回接口

来源:stackoverflow

时间:2024-02-25 18:00:27 323浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《构建一个函数映射来处理返回接口》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我有一个 go 包,其中包含大量(自动生成的)模型:

tax2001_1
tax2001_2
tax2001_3
...
tax2020_1

每个定义如下:

func newtax2011_1() *tax2011_1 {
    return &tax2011_1 { ... }
}

我想根据仅在运行时已知的值(时间戳)来访问它们。 所以我尝试将模型构造函数放入地图中:

package tax

type taxmodel interface {
  calculate()
}

var taxmodels = make(map[string]func() *taxmodel)

func init() {
  ...
  taxmodels["2011_1"] = newtax2011_1
  taxmodels["2011_2"] = newtax2011_2
  ...
}

上面的代码不正确:

cannot use NewTax2011_1 (type func() *Tax2011_1) as type func() *TaxModel in assignment

有什么提示可以实现这一点吗?


解决方案


假设tax2011_1及其朋友实现了taxmodel接口,您可以声明构造函数以返回该接口:

func newtax2011_1() taxmodel {
  return &tax2011_1{}
}

您不应该使用接口指针:

var taxmodels = make(map[string]func() taxmodel)

然后它应该可以工作。

如果无法更改构造函数,可以使用适配器函数:

func newtax2011_1() *tax2011_1 {...}

var taxmodels = make(map[string]func() taxmodel)

func init() {
  ...
  taxmodels["2011_1"] = func() taxmodel {return newtax2011_1()}
  taxmodels["2011_2"] = func () taxmodel {return newtax2011_2() }
  ...
}

这是我所做的测试,似乎有效。 看起来您不需要使用指向接口的指针。这似乎就是问题所在。

package main

import "fmt"

type Model_1 struct {
        Name string
}

type Model_2 struct {
        Name string
}

func (m *Model_1) Calculate() int64 {
        return 0
}

func (m *Model_2) Calculate() int64 {
        return 0
}

type Model interface {
        Calculate() int64
}

func main() {
        m := make(map[string]func() Model)
        m["test"] = func() Model {
                return &Model_1{Name: "m"}
        }
        fmt.Println(m["test"]().Calculate())
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>