如何正确设置 Golang 库?

How do you properly set up a Golang library?

我已经尝试了很多次使用模块系统设置一个真正的 go 包并将代码存储在 pkg 中。 All the tutorials I've found are too basic,在顶层创建一个带有 go 文件存储的模块,我不断得到 no Go files in /usr/local/go/github.com/me/mypackage

我尝试了很多不同的东西,但我无法让它正常工作...

GOROOT 设置为 /usr/local/go。我在这里创建了一个包 /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)
    }
}

而我运行:go test

我做错了什么?我发现 Go 的设置非常令人沮丧,因为 languages/runtimes 像 Rust 和 NodeJS 一样有非常友好的包管理器并且非常容易设置。

我正在尝试按照 this guidance for structuring go packages.

中的描述构建一个库

不要混淆模块和包。 一个模块可能包含多个包。 像这样:

  • module_dir/package1_dir
  • module_dir/package2_dir

试试这个布局:

存储库:github.com/me/mymodule

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

mypkg.gomypkg_test.go中声明package mypkg

否则,运行此脚本将为您创建正确的布局:

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