英文:
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("James", "Tran")
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 <???>) {
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论