Is there a way to create a function using unexported type as parameter in Golang?

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

Is there a way to create a function using unexported type as parameter in Golang?

问题

在我的应用程序中,我有一个结构体,我定义了一个New函数来创建实例,因为字段的零值没有意义。此外,我没有导出这个结构体。所以创建实例的唯一方法是通过New函数。

var goodPerson = person.New("James", "Tran")

goodPerson.PrintFullName()

在调用方面,我不知道如何创建一个函数,以这种方式接受未导出的类型作为参数,同时仍然可以访问该类型的导出方法。

func doBadThingToGoodPeople(goodPerson <???>) {
   goodPerson.PrintFullName()
}

如果你能指点我一个方向,我将非常感激。

英文:

In my application, I have a struct for which I defined a New function to create instances as zero values of the fields are not meaningful. In addition, I didn't export the struct. So the only way to create is via New.

var goodPerson = person.New(&quot;James&quot;, &quot;Tran&quot;)

goodPerson.PrintFullName()

On the caller side, I have no idea how to create a function that takes in the unexported type as a parameter in such a way that I can still access the exported methods of this type.

func doBadThingToGoodPeople(goodPerson &lt;???&gt;) {
   goodPerson.PrintFullName()
}

I'd be very grateful if you could point me in a direction.

答案1

得分: 7

你可以使用一个接口:

type FullNameSupport interface {
  PrintFullName()
}

func doBadThingToGoodPeople(goodPerson FullNameSupport) {
   goodPerson.PrintFullName()
}

这样就不需要导出类型了。

英文:

You can use an interface:

type FullNameSupport interface {
  PrintFullName()
}

func doBadThingToGoodPeople(goodPerson FullNameSupport) {
   goodPerson.PrintFullName()
}

This way don't have to export the type.

huangapple
  • 本文由 发表于 2021年7月13日 01:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/68351980.html
匿名

发表评论

匿名网友

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

确定