英文:
Wrapping a package in golang
问题
假设有一个导出一些结构体和函数的包。
如果我想要创建一个包装器,使其可以作为一个可替换的组件使用,我应该如何重新创建这些结构体?例如:
package foo
type Foo struct {
Field string
}
func DoSomething() {
}
package bar
import foo
type Foo struct {
foo.Foo
}
func DoSomething() {
foo.DoSomething()
}
有没有更好的方法?这种方式是否符合惯例?
英文:
Imagine a package that exports some structs and some functions.
If I wanted to make a wrapper around that package, so that it could be used as a drop-in, should I recreate the structs with the old struct embedded in it? Example:
package foo
type Foo struct {
Field string
}
func DoSomething() {
}
package bar
import foo
type Foo struct {
foo.Foo
}
func DoSomething() {
foo.DoSomething()
}
Is there a better way? Is this the idiomatic way?
答案1
得分: 1
我认为不需要。只需使用原始包,如果你想使用自己的版本,可以使用别名。
假设你的代码当前是这样的:
import (
"abc.com/package/foo"
)
func CallFoo() {
foo.DoSomething()
}
你可以通过给导入的包设置别名来将 foo 替换为 bar,其他代码保持不变。
import (
foo "abc.com/package/bar" // 这是别名
)
func CallFoo() {
foo.DoSomething()
}
英文:
I think not. Just use the original package, you could use alias if you want to use your own version.
Let's say currently your code is:
import (
"abc.com/package/foo"
)
func CallFoo() {
foo.DoSomething()
}
You can replace foo with bar by alias the import, other codes remain the same.
import (
foo "abc.com/package/bar" // this is alias
)
func CallFoo() {
foo.DoSomething()
}
答案2
得分: 1
似乎这是惯用的方式。没有魔法。
func DoSomething() {
foo.DoSomething()
}
英文:
Seems like this is the idiomatic way. No magic.
func DoSomething() {
foo.DoSomething()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论