Golang中在main.go中导入一个本地子包的方法

93 阅读1分钟

大家好,我是golang的初学者,我对模块管理感到非常困惑,当我试图导入本地包并使用参数时,我得到了错误。这实在是太奇怪了!

我的golang环境设置如下

GO111MODULE="on"
GOPATH="/root/go"
GOROOT="/usr/local/go"
GOVERSION="go1.18.2"

我的文件夹看起来像这样。

test-module
--dir1
----dir1.go
--go.mod      
--main.go     

文件main.go导入了dir1包并打印了a的参数。

main.go

  1 package main
  2 import(
  3     "fmt"
  4     "test-module/dir1"
  5 )
  6
  7 func main(){
  8     fmt.Println(dir1.a)
  9 }

go.mod

module test-module

go 1.18

dir1.go

package dir1

var a = 2

而当我试图运行主文件时。(go run main.go)时,出现了错误提示。

# command-line-arguments
./main.go:8:19: undefined: dir1.a