多重指针

huangapple go评论84阅读模式
英文:

GO Multiple Pointers

问题

我正在尝试创建一个函数,该函数接收多种类型的结构体,并将这些指针值添加到另一个函数中。

示例:

type Model1 struct {
  Name string
}

type Model2 struct {
  Type bool
}

func MyFunc(value ...interface{}) {
  OtherFunc(value...)
}

func main() {
  MyFunc(new(Model1), new(Model2))
}

问题是OtherFunc只允许&value, &value等作为参数。有没有办法像OtherFunc(&value...)这样传递这些值?

英文:

I'm trying to create a function that receives multiple types of struct and add those pointer values to another function.

> Example:

<!-- language: lang-go -->

type Model1 struct {
  Name string
}

type Model2 struct {
  Type bool
}

func MyFunc(value ...interface{}) {
  OtherFunc(value...)
}

func main() {
  MyFunc( new(Model), new(Mode2) );
}

The problem is that OtherFunc only allow &amp;value, &amp;value, etc as parameter. Have some way to pass those values like OtherFunc(&amp;value...)?

答案1

得分: 3

我不确定这个方法能完全解决你的问题,但是你所要求的确实是语言的一个特性。你只需要使用复合字面量语法来实例化,而不是使用new关键字。所以你可以这样传递指针:MyFunc(&Model{}, &Mode2{})

问题是,在MyFunc内部你仍然需要处理一个interface{}类型,所以我不确定是否能直接调用OtherFunc而不需要进行一些拆箱操作(如果你想要技术上的说法,可能需要进行类型断言)。

英文:

I'm not sure this will solve your problem entirely however, the exact thing you requested is a feature in the language. You just have to use composite-literal syntax for instantiation instead of new. So you could do this to pass pointers; MyFunc( &amp;Model{}, &amp;Mode2{} )

Thing is, you're still going to be dealing with an interface{} within MyFunc so I'm not sure that will just be able to call OtherFunc without some unboxing (would probably be a type assertion if you want to get technical).

huangapple
  • 本文由 发表于 2015年10月28日 00:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/33374061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定