登录
首页 >  Golang >  Go问答

有没有办法改变函数的参数结构?

来源:stackoverflow

时间:2024-03-06 10:36:26 244浏览 收藏

本篇文章向大家介绍《有没有办法改变函数的参数结构?》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我有一些函数可以通过通道将结构传递到其他函数,这些函数的不同之处仅在于其通道接受的结构。我希望拥有一组可以更改通道传递的结构类型的函数。

例如,在下面的代码中,我希望能够在传递类型 a 或类型 b 的通道之间切换。根据我在接口上读到的内容,我可以根据结构类型选择不同的方法,但我最终仍然会得到两组或更多组类似的函数。

我已经研究了 make(chan interface{}) 和 reflect,但如果可能的话,我想指定编译类型。我还缺少其他方法吗?

https://play.golang.org/p/uz-eo6pdqux

type A struct{
  Name string
  Date time.Time
}
type B struct{
  Name string
  Height string
}
func onealpha (a1 <-chan A, a2 chan<- A){
    for x:=range a1{
        fmt.Printf("%+v",x)
        a2<-x
    }

}
func onebeta (b1 <-chan B, b2 chan<- B){
    for x:=range b1{
        fmt.Printf("%+v",x)
        b2<-x
    }

}
func twoalpha(a2 <-chan A){
    <-a2
}
func twobeta(b2 <-chan B){
    <-b2
}
func main() {
    a1:=make(chan A)
    a2:=make(chan A)
    b1:=make(chan B)
    b2:=make(chan B)

    go onealpha(a1,a2) //receives from a1, does some stuff and sends to a2
    go onebeta(b1,b2)  //receives from b1, does the same stuff and sends to b2

    a1<- A{Name:"Bob"}
    b1<- B{Name:"Marsha"}

    twoalpha(a2)  
    twobeta(b2)  
}

解决方案


您可以尝试从您的类型中提取接口,例如:

type I interface {
   GetName() string
}

type A struct{
  Name string
  Date time.Time
}

type B struct{
  Name string
  Height string
}

func (a A) GetName() string { return a.Name }
func (b B) GetName() string { return b.Name }

func onealpha (a1 <-chan I, a2 chan<- I){
    for x:=range a1 {
        fmt.Printf("%+v",x.GetName())
        a2 <- x
    }
}

但是,是的,正如上面提到的:没有泛型这是不可能的。

对此有一些解决方案:反射和代码生成。

本篇关于《有没有办法改变函数的参数结构?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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