dongzouhe9734
dongzouhe9734
2018-04-23 06:54

如何在golang中使用本地包? [重复]

已采纳

This question already has an answer here:

Here are two .go files.

├── lib.go
└── main.go

The lib.go has a package libtest.

$ cat lib.go 

package libtest

import (
    "fmt"
)

func TestLibFunc() {
    fmt.Println("This is test library function")
}

The main.go has a package main.

$ cat main.go
package main

import (
    "libtest"
)

func main() {
    libtest.TestLibFunc()
}

When I tried to build them, but it's failed.

$ go build *.go
can't load package: package main: found packages libtest (lib.go) and main (main.go) in /Users/dev/work/tmp/local-package

How can I use local packages in main package?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duan41497 duan41497 3年前

    You need to put each package in a separate sub-directory. So your directory structure so put lib.go in project/lib and main.go in project/cmd. It should then work.

    点赞 评论 复制链接分享
  • duanguangsong2380 duanguangsong2380 3年前

    First of all create a separate package libtest and put lib.go there. Then you should give the full path of libtest otherwise your import right now searches for $GOPATH/src/libtest or /usr/local/Cellar/go/<version> which doesn't exist.

    So you should give import project/libtest

    点赞 1 评论 复制链接分享

相关推荐