Bussiere
Bussiere

Reputation: 1144

Multiple file project in golang

I have a project with 2 files :

enter image description here

Here is my main.go file :

package main

import "fmt"
import "math"

func main() {
    xs := []float64{1, 2, 3, 4}
    avg := math.Average(xs)
    fmt.Println(avg)
}

and my math.go :

package math

func Average(xs []float64) float64 {
    total := float64(0)
    for _, x := range xs {
        total += x
    }
    return total / float64(len(xs))
}

But when i do :

> bussiere@kusanagi [06:44:01 PM] [~/Workspace/bdrun/TestPack/src]
> -> % go install .
> # _/home/bussiere/Workspace/bdrun/TestPack/src ./main.go:8:9: undefined: math.Average bussiere@kusanagi [06:47:12 PM]
> [~/Workspace/bdrun/TestPack/src]-> % go run main.go
> # command-line-arguments ./main.go:8:9: undefined: math.Average

How comes ?

Regards and thanks

Upvotes: 0

Views: 1853

Answers (1)

Corey Ogburn
Corey Ogburn

Reputation: 24717

You're close. What you have:

bin/
pkg/
  math.go
src/
  main.go

But this isn't what the go binary expects. Under the src folder should be a folder for each project:

src/
  myproject/
    math/
      math.go
    main.go

When you want a go file to be in a different package it should be in a folder of the same name as the new package. You'll need to update your math import. import "math" will import the standard library math file. Try import "myproject/math" in your main.go after making the tree structure above.

You don't have to worry about the pkg or bin folder. You won't normally need to go out of your way to put anything in them.

Upvotes: 4

Related Questions