Export functions from internal package in Go

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

Export functions from internal package in Go

问题

我正在测试将大部分代码放在一个internal包中,然后选择性地将其中的方法/类型暴露给外部世界。代码看起来像这样:

/mypackage/internal/catapult

package catapult

func Load(boulder Boulder) {
  // ...
}

func Trigger() *Launch {
  // ...
}

// ...

也许Load被其他内部包(/mypackage/internal/randomevents/boredsoldier/mypackage/internal/actualattackstrategy)调用,但不应该被internal以外的用户调用。所有这些包只允许在加载弹弓后触发它。

现在,我想在internal上面有一个包(/mypackage/general),其中Trigger被公开,但Load不被公开。我希望能做到这样:

package general

const TriggerCatapult = catapult.Trigger
// ^ 这样做不起作用,因为函数不能是常量

var TriggerCatapult = catapult.Trigger
// ^ 从技术上讲可以工作,但现在 TriggerCatapult 的值可以被任何包的用户覆盖

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}
// ^ 这样可以工作。只是每次都要重新编写整个函数的签名有点“痛苦”

有更好的方法吗?

英文:

I'm testing the idea of putting most of my code in an internal package and then picking exactly which of the methods / types from there I'm exposing to the outside world. Code would look like:

/mypackage/internal/catapult

package catapult

func Load(boulder Boulder) {
  // ...
}

func Trigger() *Launch {
  // ...
}

// ...

Maybe Load is being called by other internal packages (/mypackage/internal/randomevents/boredsoldier and /mypackage/internal/actualattackstrategy) but shouldn't be allowed by users outside of internal. All those are allowed to do is Trigger the catapult once it's loaded.

So now I'd like to have a package above internal (/mypackage/general) where Trigger is exposed but not Load. I was hoping to do something like:

package general

const TriggerCatapult = catapult.Trigger
// ^ does not work because a function cannot be a const

var TriggerCatapult = catapult.Trigger
// ^ technically works but now the value of TriggerCatapult can be overwritten by any package user

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}
// ^ works. It's just "painful" to have to reproduce the entire function's signature every time

Is there a better way to do this?

答案1

得分: 1

不,你提供的方式是没有更好的方法来做这个的:

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}

不过,你不应该返回未导出的类型,大多数代码检查工具会为你捕捉到这个问题。

如果用户要直接与catapult中的内容进行交互,那么该包就不应该是内部的。

英文:

No, there is no better way to do this that the way you provide:

func TriggerCatapult() *catapult.Launch {
    return catapult.Trigger()
}

You shouldn't return unexported types though, and most linters would catch this for you.

If a user is going to interact directly with things in catapult, then that package should not be internal.

huangapple
  • 本文由 发表于 2022年5月20日 00:55:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/72308401.html
匿名

发表评论

匿名网友

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

确定