Go 1.13.3项目构建报错:目录布局异常求助
Hey, let's fix this annoying build error you're hitting. From your build logs and go env output, the issue boils down to a mismatch between your project's directory structure and how Go expects to find packages (either via GOPATH mode or Modules). Here's what's going on and how to fix it:
What's Causing This?
- You've got
GO111MODULE="", which means Go is falling back to the old GOPATH mode. - Your GOPATH is set to
/home/username/Projects/Proj1, but your project lives at/home/username/Projects/golangProject/src/ip—this path isn't inside thesrcdirectory of your configured GOPATH. Go can't resolve the import path correctly, hence the "unexpected directory layout" error.
Two Fixes (Option 2 is Recommended)
Option 1: Adjust Directory Structure for GOPATH Mode
If you want to stick with GOPATH:
- First, make sure the
srcdirectory exists in your GOPATH:mkdir -p /home/username/Projects/Proj1/src - Move your project's
ippackage into thissrcdirectory:mv /home/username/Projects/golangProject/src/ip /home/username/Projects/Proj1/src/ - Navigate to the package directory and rebuild:
cd /home/username/Projects/Proj1/src/ip /usr/local/go/bin/go install -v -gcflags "-N -l" ./...
Option 2: Use Go Modules (Modern, Recommended Approach)
Go 1.13 fully supports Modules, which lets you work outside GOPATH. This is the standard way to manage Go projects now:
- Go to your project's root directory (not the
src/ipsubdir):cd /home/username/Projects/golangProject - Initialize a Go module (you can use any name here, like your project's repo URL or a custom name):
go mod init golangProject - Run your build command again—this should work now:
/usr/local/go/bin/go install -v -gcflags "-N -l" ./... - (Optional) To make Modules the default for all your projects, set
GO111MODULE=onpermanently:echo 'export GO111MODULE=on' >> ~/.bashrc source ~/.bashrc
Verify It Works
After trying either option, re-run your build command. If you don't see that directory layout error anymore, you're good to go! You can double-check your config with go env to confirm everything's set up correctly.
内容的提问来源于stack exchange,提问作者sandip kumar

