On Thu, Jun 9, 2022 at 5:18 PM jlfo...@berkeley.edu <jlforr...@berkeley.edu> wrote:
> I'm having trouble understanding what should be a trivial issue. > > I have the following file structure: > > . > ├── go.mod > ├── main.go > ├── p1 > │ └── p1.go > └── p2 > └── p2.go > > The files are small and simple. > > -- go.mod > module wp > > go 1.18 > > -- main.go > // main.go > package main > > import ( > "wp/p1" > "wp/p2" > ) > > func main() { > p1.P() > p2.P() > } > > -- p1/p1.go > // p1.go > package p1 > > import ( > "fmt" > "wp/p2" > ) > > func P() { > fmt.Printf("p1\n") > p2.P() > } > > -- p2.go > // p2.go > package p2 > > import ( > "fmt" > "wp/p1" > ) > > func P() { > fmt.Printf("p2\n") > p1.P() > } > > > In main.go I'm trying to call a function in packages p1 and p2. In package > p1 p1.go is trying to call a function in package p2, and in package p2 > p2.go is trying to call a function in package p1. Simple, right? > > However, running "go build ." in the top level directory says: > > package wp > imports wp/p1 > imports wp/p2 > imports wp/p1: import cycle not allowed > > Is this because p1 imports p2, which imports p1, which imports p2, ...? > Yes. From https://go.dev/ref/spec#Import_declarations: > It is illegal for a package to import itself, directly or indirectly, or to directly import a package without referring to any of its exported identifiers. > How can this program be made to work? I've tried many things, which all > lead back > to the situation I describe above. > You need to refactor the code to eliminate the import cycle. Exactly how you do that depends on specifics of the situation which you haven't shared. If you google "golang import cycle not allowed" you'll find many articles and stackoverflow questions that discuss this. For example: https://jogendra.dev/import-cycles-in-golang-and-how-to-deal-with-them https://quoeamaster.medium.com/golang-gotchas-2-the-curse-of-import-cycle-not-allowed-6abfa3523f57 -- Kurtis Rader Caretaker of the exceptional canines Junior and Hank -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD-thv0c2OED%2BG5DrbuTciAhw468%2B%2BKSgmQS7aog3oK2%3Dw%40mail.gmail.com.