Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build and reference my own local package in Go

Tags:

I'm playing with Google Go and I'm having fun (!), but I'm having some problems with package subsystem.

I'm running Go 1.0.1 on Mac OS X Lion. I've build also various single file programs without problems (I've also build a small webapp using html/templates without problems and it compiles and runs without any error).

I've defined a "reusable" package (even.go):

package even

func Even(i int) bool {
    return i % 2 == 0
}

func Odd(i int) bool {
    return i % 2 == 1
}

and a consumer program (useeven.go):

package main

import (
    "./even"
    "fmt"
)

func main() {
    a := 5
    b := 6

    fmt.Printf("%d is even %v?\n", a, even.Even(a))
    fmt.Printf("%d is odd %v?\n", b, even.Odd(b))
}

But when I compile the "library" using

go build even.go

I got nothing... No errors, no message... What happens?

How should I do this?

like image 972
gsscoder Avatar asked May 02 '12 15:05

gsscoder


People also ask

How do I import a package into 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.


2 Answers

The answer to your question, "How should I do this?" is explained in How to Write Go Code. It's really pretty important stuff and worth taking a look at.

The behavior of go build might seem puzzling, but is actually conventional for command line programs--no output means that the program ran successfully. So what did it do? For that your answer is in go help build

... Otherwise build compiles the packages but discards the results, serving only as a check that the packages can be built.

What, you wanted more? Of course. "How to Write Go Code" explains good ways of doing this. For a quick fix to your program, I'll explain that the go command expects each package and each executable program to be in a separate directory. If you just make a directory called even, immediately under the location of useeven.go, and move even.go to it, then go run useeven.go should run just as you have it.

like image 87
Sonia Avatar answered Oct 13 '22 06:10

Sonia


go build only generates an output file when it builds a "single main package". If you want to output a file for your other package you should use go install. That will build and install that package to your pkgs directory.

like image 45
Code Commander Avatar answered Oct 13 '22 06:10

Code Commander