Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building package structure with child-/sub-packages

Tags:

package

go

I'm trying to make a simple calculator in Go. I'm designing it in such a way that I can build a command-line interface first and easily swap in a GUI interface. The project location is $GOPATH/src/gocalc (all paths hereafter are relative to the project location). The command-line interface logic is stored in a file gocalc.go. The calculator logic is stored in files calcfns/calcfns.go and operations/operations.go. All files have package names identical to their filename (sans extension) except the main program, gocalc.go, which is in the package main

calcfns.go imports operations.go via import "gocalc/operations"; gocalc.go imports calcfns.go via import "gocalc/calcfns"

To summarize:

  • $GOPATH/src/gocalc/
    • gocalc.go
      • package main
      • import "gocalc/calcfns"
    • calcfns/
      • calcfns.go
        • package calcfns
        • import "gocalc/operations"
    • operations/
      • operations.go
        • package operations

When I try to go build operations (from the project dir), I get the response: can't load package: package operations: import "operations": cannot find package When I try go build gocalc/operations, I get can't load package: package gocalc/operations: import "gocalc/operations": cannot find package When I try go build operations/operations.go, it compiles fine

When I try to go build calcfns or go build gocalc/calcfns, I get can't load package... messages, similar to those in operations; however, when I try to build calcfns/calcfns.go it chokes on the import statement: import "gocalc/operations": cannot find package

Finally, when I try go build . from the project dir, it chokes similar to the previous paragraph: import "gocalc/calcfns": cannot find package

How should I structure my child packages and/or import statements in such a way that go build won't fail?

like image 637
weberc2 Avatar asked Jan 19 '13 18:01

weberc2


1 Answers

Stupidly, I forgot to export my GOPATH variable, so go env displayed "" for GOPATH. (thanks to jnml for suggesting to print go env; +1).

After doing this (and moving the main program to its own folder {project-dir}/gocalc/gocalc.go), I could build/install the program via go install gocalc/gocalc.

Moral of the story, make sure you type export GOPATH=... instead of just GOPATH=... when setting your $GOPATH environment variable

like image 102
weberc2 Avatar answered Nov 13 '22 07:11

weberc2