Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing local library and files in an application

Tags:

package

go

I'm new to Go (but not at programming), I love the language but I have a bit of trouble fully understanding the way I'm supposed to make internal libraries in an application through packages. For reference, getting external packages and then importing/using them is fine.

Let's say I'm making an application A.

/home/me/A/a.go (package main)

Then, I realize a.go start to be rather big, so I cut it into two parts

/home/me/A/a.go (package main)
/home/me/A/b.go (package main)

How am I supposed to import/include b.go from a.go to make its function available ?

As a continuation of the question, in the A I'm manipulation lots of objects O, so I figure it would be a lot better if I just give them their own package and encapsulate the functionalities in a public/exported api. How do I do that ?

I've tried creating ./lib/o.go (package o) and import lib/o but I keep getting error like

./a.go:6: imported and not used: "o"
./a.go:43: undefined: o

I have no GOPATH in my env but I tried export GOPATH=$GOPATH:/home/me/A and it didn't change the result.

I've tried to read the article on "go layout" but it felt a bit too overwhelming at once and I would really love a simpler explanation of that one "small" step I am trying to make

Thanks !

GOPATH/src/me/a/a.go:

package main

func main() {
        test()
}

GOPATH/src/me/a/test.go:

package main

import "fmt"

func test() {
        fmt.Println("test func !")
}

Exec:

$ go run a.go 
# command-line-arguments 
./a.go:4: undefined: test

EDIT: got my answer here: https://groups.google.com/forum/?fromgroups#!topic/golang-nuts/qysy2bM_o1I

Either list all files in go run (go run a.go test.go) or use go build and run the resulting executable.

like image 479
user933740 Avatar asked May 26 '13 14:05

user933740


People also ask

How do I import packages to go?

To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.


1 Answers

You're trying to use the Go build system while not following the necessaary required directory layouts. You will benefit a lot from reading this document.

In short, these are, wrt the go tool, the show stoppers:

  • You must have a valid, exported GOPATH

  • Package files with import path "example/foo" must be located in the $GOPATH/src/example/foo directory.

For more details please see the above linked article.

like image 62
zzzz Avatar answered Nov 15 '22 23:11

zzzz