Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import and not used error

Tags:

go

I'm getting below error with below import code:

Code: package main

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

Error:

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

Is there a reason why the import is not working given that I have package api and files stored under api folder?

I'm using below to use api in 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)
}
like image 922
Passionate Engineer Avatar asked Sep 19 '14 01:09

Passionate Engineer


2 Answers

The compiler looks for actual use of a package .. not the fact it exists.

You need to use something from that package.. or remove the import. E.g:

v := api.Something ...

If you don't use anything from that package in your source file .. you don't need to import it. That is, unless you want the init function to run. In which case, you can use the ignore notation import _.

EDIT:

After your update, it appears you're overwriting the package import here:

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

That declares a variable called api. Now the compiler thinks its a variable, and so you're not actually using the api package.. you're using the api variable.

You have a few options.

Firstly, you can call that variable something else (probably what I would do):

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

Or, alias your import (not what I would do.. but an option nonetheless):

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

The problem is that the compiler is confused on what to use. The api package.. or the api variable you have declared.

You should also import the package via the GOPATH instead of relatively.

like image 180
Simon Whitehead Avatar answered Sep 25 '22 02:09

Simon Whitehead


First of all, don't use relative imports.

If your GOPATH contains /Users/aaaa/IdeaProjects/app/src, then import your package as api.

Next, you're shadowing api with the assignment to api :=. Use a different name.

like image 44
JimB Avatar answered Sep 24 '22 02:09

JimB