【问题标题】:Import and not used error导入且未使用错误
【发布时间】:2021-09-11 00:38:33
【问题描述】:

以下导入代码出现以下错误:

代码: 主包

import (
    "log"
    "net/http"
    "os"
    "github.com/emicklei/go-restful"
    "github.com/emicklei/go-restful/swagger"
    "./api"
)

错误:

.\main.go:9: imported and not used: "_/c_/Users/aaaa/IdeaProjects/app/src/api"

鉴于我有 package api 和存储在 api 文件夹下的文件,是否有导入无法正常工作的原因?

我在下面使用 api 在 main.go 中

func main() {
    // to see what happens in the package, uncomment the following
    restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))

    wsContainer := restful.NewContainer()
    api := ApiResource{map[string]OxiResp{}}
    api.registerLogin(wsContainer)
    api.registerAccount(wsContainer)
    api.registerLostLogin(wsContainer)
    api.registerWallet(wsContainer)
}

【问题讨论】:

    标签: go


    【解决方案1】:

    编译器寻找包的实际使用 ..而不是它存在的事实。

    您需要使用该包中的某些内容.. 或删除导入。例如:

    v := api.Something ...
    

    如果您在源文件中不使用该包中的任何内容..您不需要导入它。也就是说,除非您希望 init 函数运行。在这种情况下,您可以使用忽略符号import _

    编辑:

    更新后,您似乎在此处覆盖了包导入:

    api := ApiResource{map[string]OxiResp{}}
    

    这声明了一个名为api 的变量。现在编译器认为它是一个变量,所以你实际上并没有使用api 包。你正在使用api 变量。

    你有几个选择。

    首先,您可以将该变量称为其他名称(可能我会这样做):

    apiv := ApiResource{map[string]OxiResp{}}
    

    或者,为您的导入设置别名(不是我会做的......但仍然是一个选项):

    import (
        // others here
        api_package "./api"
    )
    

    问题是编译器对使用什么感到困惑。 api 包.. 或您已声明的 api 变量。

    您还应该通过GOPATH 导入包,而不是相对。

    【讨论】:

      【解决方案2】:

      首先,不要使用相对导入。

      如果您的GOPATH 包含/Users/aaaa/IdeaProjects/app/src,则将您的包导入为api

      接下来,您将通过分配给api := 来跟踪 api。使用不同的名称。

      【讨论】:

        【解决方案3】:

        如果您的 .go 文件存在阻止编译器到达使用它的位置的错误,则可能会发生此错误。

        【讨论】:

          猜你喜欢
          • 2015-05-18
          • 2015-06-21
          • 2017-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多