英文:
golang undefined function call on imported library
问题
我已经导入了github.com/mitchellh/mapstructure
库到我的项目中。然而,我无法使用该库中的Decode函数将一个map接口转换为struct:
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
这个基本的调用返回了一个"undefined: Decode"错误。除了导入之外,还需要做其他的事情吗?
提前感谢!
英文:
I've imported
_ "github.com/mitchellh/mapstructure"
Into a project of mine. However i'm not able to utilize the Decode function included in that library in order to convert a map interface to struct:
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
This basic call returns "undefined: Decode" error. Is there anything else to be done besides the import?
Thanks in advance!
答案1
得分: 9
如果你使用下划线作为导入包的第一个参数,那么你将无法使用该包的任何函数或类型。下划线表示你只是为了调用init()函数而导入该包的副作用。
此外,在这种情况下,你需要在函数名之前使用包名,比如mapstructure.Decode。
另外,正如Ainar-G指出的那样,你可以在导入包时使用“.”代替下划线。这样你将把名称导入到“default”命名空间中,可以直接使用Decode。然而,这并不推荐,因为这样会污染命名空间并可能导致冲突,现在或将来。
英文:
If you import a package with _ as first argument, you cannot use any function or type of that package. _ means that you are importing the package only for its secondary effects of calling the init() functions.
In addition, you need to use the package name before the function, mapstructure.Decode in this case.
Alternatively, as pointed out by Ainar-G, you may use "." instead of _ when importing the package. This way you will be importing the names to the "default" namespace, allowing to use Decode directly. However, this is not recommended because you are polluting the namespace with other names and there may be conflicts, now or in the future.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论