Some Go text editors and IDEs (in my particular case, JetBrains's GoLand IDE) will automatically delete unused imports on save. This is ordinarily a good thing, because the Go compiler throws errors for unused imports.
However, in the case of the github.com/fxamacker/cbor/v2
import, I believe GoLand gets confused by the v2
at the end, and thinks the import is never used, because there is never any v2.<something>
in the file anywhere. So GoLand deletes this import when I save, but then my file fails to compile, because the import I need is gone.
I thought I could fix this with a leading underscore, like this:
import (
// ... other imports here ...
_ "github.com/fxamacker/cbor/v2"
)
When I make this change, then GoLand does not delete my import, but then I get errors when I compile:
redacted.go:15:10: undefined: cbor redacted.go:19:13: undefined: cbor redacted.go:20:17: undefined: cbor redacted.go:109:8: undefined: cbor
How can I import this module so that the import isn't auto-deleted by GoLand, and the file can still be compiled?
CodePudding user response:
I just created a project with Goland using cbor/v2
and everything works as expected. I think that you have another configuration problem which is unrelated to that package or Go versioning.
How to reproduce:
In new directory:
$ go mod init q
go: creating new go.mod: module q
$ go get github.com/fxamacker/cbor/v2
go: downloading github.com/fxamacker/cbor v1.5.1
go: downloading github.com/fxamacker/cbor/v2 v2.4.0
...
- Open that directory as a project in Goland.
- Create file main.go with contents
package main
func main() {
var dummy int
cbor.Marshal(dummy)
}
Goland will add
import "github.com/fxamacker/cbor/v2"
And saving does not remove it.
CodePudding user response:
I found I can do this like this:
import (
// ... other imports here ...
cbor "github.com/fxamacker/cbor/v2"
)
Then GoLand can see that the import is in use, and Go still has a name for the module so it can compile the code.
The issue with my underscore approach in my question was that then Go has no name for the module, which causes it to not recognize cbor.something
in the file.