在Go语言中包装一个包(Wrapping a package in golang)

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

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()
}

huangapple
  • 本文由 发表于 2017年1月3日 16:39:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/41439435.html
匿名

发表评论

匿名网友

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

确定