首页 > 后端开发 > Golang > 正文

为什么在 Go 中导入特定类型时出现'已导入但未使用”和'未定义”错误?

Mary-Kate Olsen
发布: 2024-11-15 12:03:02
原创
193 人浏览过

Why Am I Getting

Import Package and Type

Question:

In the following project structure:

src
|-->config
       |--> config.go
|-->otherPackage
       |--> otherFile.go
|-->main.go
登录后复制

There is a type defined in config.go that needs to be used in otherFile.go. However, attempting to import it using the following statement results in errors:

import (
    "fmt"
    "math"
    "../config"
)
登录后复制

The specific errors are:

  • Imported and not used.
  • Undefined: Config

Even though the type Config is used in a function declaration.

What is the underlying problem?

Answer:

The issue stems from trying to import only a specific type from a package. In Go, it is not possible to import specific elements from a package. When importing a package, you are essentially importing its entire contents.

In this case, since the package where the Config type is defined is named config, importing it will make its types and other identifiers available under the config namespace. For instance, to use Config, it must be referenced as config.Config.

Therefore, to resolve the problem, one of the following solutions can be employed:

  • Rename the config variable: Since in otherFile.go there is a variable named config, which shadows the imported package, it should be renamed to avoid conflicts.
  • Reference Config using the qualified name: If renaming is not an option, then the type Config can still be used by referencing it with its qualified name, which would be config.Config.

以上是为什么在 Go 中导入特定类型时出现'已导入但未使用”和'未定义”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板