求助:Golang同一代码在不同文件夹编译,一个正常一个报找不到包"."错误
Fixing the "cannot find package "."" Error in Your Second Go Project
Hey there, let's break down why your second Go project is hitting that error while the first one works perfectly—even though the code's identical. The issue almost always boils down to how Go handles package discovery, specifically with Go modules or the old GOPATH workspace setup.
Why This Happens
Go needs clear context to recognize your code as a valid package. Here's what’s likely going on:
- Your first project folder is either inside your
GOPATH/srcdirectory (the legacy workspace mode) or has already been initialized as a Go module (it has ago.modfile). - Your second project folder is neither in
GOPATH/srcnor has ago.modfile, so Go can’t resolve the local package correctly.
Step-by-Step Fix (Modern Go Module Approach)
This is the recommended method for current Go versions:
- Navigate to your second project directory in your terminal:
cd E:/Clouds/OneDrive/CX/GoLang/test - Initialize a Go module for the project. You can use any name here (for local projects, even something simple like
testworks):
This creates ago mod init testgo.modfile in the folder, telling Go this is a standalone, valid module. - Run your build command again:
This should compile successfully, just like your first project.c:/go/bin/go.exe build -i E:/Clouds/OneDrive/CX/GoLang/test
Alternative: Legacy GOPATH Mode
If you prefer sticking to the older workspace system:
- Run
go env GOPATHto check your current GOPATH directory. - Move your second project into the
srcsubfolder of that GOPATH. For example, if your GOPATH isE:/Clouds/OneDrive/CX/GoLang, your project should live atE:/Clouds/OneDrive/CX/GoLang/src/test. Nogo.modfile is needed here.
Quick Edge Case Checks
If the above doesn’t work, verify:
- Your OneDrive folder has finished syncing (partial syncs can cause hidden file access issues).
- The folder has write permissions (Go needs to create temporary files during compilation).
内容的提问来源于stack exchange,提问作者Jonathan Hecl
相关产品推荐
相关产品推荐

