Home > Blockchain >  How do you properly set up a Golang library?
How do you properly set up a Golang library?

Time:04-26

I've tried many times to set up a REAL go package with the modules system and store code in pkg. All the tutorials I've found are too basic, creating a module with go files stores at the top level, and I keep getting no Go files in /usr/local/go/github.com/me/mypackage.

I've tried a bunch of different things, but I can't get it to work properly...

GOROOT is set to /usr/local/go. I created a package here /usr/local/go/github.com/me/mypackage.

go.mod

module github.com/me/mypackage

go 1.18

pkg/main.go

package mypackage

// Add is our function that sums two integers
func Add(x, y int) (res int) {
    return x   y
}

// Subtract subtracts two integers
func Subtract(x, y int) (res int) {
    return x - y
}

pkg/main_test.go

package mypackage

import "testing"

func TestAdd(t *testing.T){

    got := Add(4, 6)
    want := 10

    if got != want {
        t.Errorf("got %q, wanted %q", got, want)
    }
}

And I run: go test

What am I doing wrong? I find Go so frustrating to set up because languages/runtimes like Rust and NodeJS have very friendly package managers and are real easy to setup.

I'm trying to structure a library as described in this guidance for structuring go packages.

CodePudding user response:

Don't confuse modules with packages. One module might hold many packages. Like this:

  • module_dir/package1_dir
  • module_dir/package2_dir

Try this layout:

Repository: github.com/me/mymodule

mymodule/mypkg
mymodule/mypkg/mypkg_test.go
mymodule/mypkg/mypkg.go
mymodule/go.mod

In mypkg.go and mypkg_test.go declare package mypkg.

Otherwise, run this script and it will create a correct layout for you:

https://gist.github.com/udhos/695d3be51fb4c7d151b4e252cdec3c63

  •  Tags:  
  • go
  • Related