Using modules, newly installed package cannot be referenced within project

Viewed 1298

go version go1.11.4 darwin/amd64 GOPATH has been unset but was previously set to $HOME/Development/go

Project path is under $HOME/code/

I’m able to successfully (no errors at least) install the go-sql-driver/mysql package using the command

go get github.com/go-sql-driver/mysql@v1

When I include a reference to that package in an import statement

import(
_ "github.com/go-sql-driver/mysql")

in my code I see the error

could not import github.com/go-sql-driver/mysql (can’t find import: “github.com/go-sql-driver/mysql”)

I have run go mod init in my project root and it creates a go.mod file. When I run the go get command I see a require statement added to that file for the package. But it seems the files for the package get installed in the default $HOME/go directory (since I've unset GOPATH).

Should I be doing things differently so that my import statement can find the newly installed package? Using modules shouldn't all the packages be installed in the project path somewhere?

2 Answers

Should I be doing things differently so that my import statement can find the newly installed package?

No. With modules there is no need to install the packages upfront at all.

Using modules shouldn't all the packages be installed in the project path somewhere?

No. They get downloaded somewhere in some format and used from that location but they are not "installed" like in the old GOPATH variant of go get.

Show output of go env and what go mod vendor produces.

I'm pretty sure I was doing things wrong. I was able to resolve this after referencing the following closely the steps documented at golang modules wiki. The summary is that there is no need to "install" a package via 'go get'. Instead simply make sure your project is initialized to use modules using the 'go mod init' command and then include the package name in an import statement. The next build event will pull down the package and all its dependencies.

Related