S
S
Sergey Ivanov2015-02-02 08:48:08
go
Sergey Ivanov, 2015-02-02 08:48:08

How to make a package in golang?

Hello. Can you please tell me how to make a package for Go?
I just started to study and configure the project as I stumbled upon understanding the creation of a package.
> echo $GOROOT
> /home/sergey/go
directory structure

  • go
    • index.go
  • src
    • pkg
      • test
        • test.go
  • bin
82e2985e541944ef92762daeb03514cb.png
index.go content
package main

import "fmt"
import "test"

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

test.go content
package test

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

~
/go/src/pkg/test$ go install
package test
imports runtime: cannot find package "runtime" in any of:
/home/sergey/go/src/pkg/runtime (from $GOROOT)
($GOPATH not set)
------------------------------------
~/go$ go run index.go
index .go:3:8: cannot find package "fmt" in any of:
/home/sergey/go/src/pkg/fmt (from $GOROOT)
($GOPATH not set)
package runtime: cannot find package "runtime" in any of:
/home/sergey/go/src/pkg/runtime (from $GOROOT)
($GOPATH not set)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Kovalev, 2015-02-02
@Writerim

imports runtime: cannot find package "runtime" in any of:
indicates that the standard libraries cannot be found, which means that either GO itself is installed crookedly or the paths are crookedly spelled out.
What gives

go env
?

U
uvelichitel, 2015-02-02
@uvelichitel

On a canonical Go installation, the ~/go/src/pkg/ $GOROOT/src/pkg/ directories should not exist at all. My advice - demolish everything and install cleanly from the source. The 'install from source' procedure is well documented and is rarely difficult. GOROOT will default to /usr/local/go (you can of course expand to home too ). GOPATH, although it can be inside GOROOT , does not have to, they are not related at all. Inside GOROOT and GOPATH there will be src and pkg directories - for sources and built libraries, respectively. pkg should not be inside src.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question