简体   繁体   中英

How do I make go find my package?

Where should I put my package so that it can be imported by another package?

$ tree
.
├── main.go
└── src
    └── test.go

1 directory, 2 files

$ cat src/test.go 
package test

$ cat main.go 
package main

import "test"

$ go build main.go 
main.go:3:8: import "test": cannot find package

There are a few things that need to happen. You must install the "test" package first:

$ export GOPATH=$(pwd)   # Assumes a bourne shell (not csh)
$ mkdir src/test
$ mv src/test.go src/test/test.go
$ mkdir pkg                 # go install will put packages here
$ go install test           # build the package and put it in $GOPATH/pkg
$ go build main.go

Note that it is not necessary to create pkg, as go install will do that for you. Once you've installed the test package (generally a bad name, BTW) go build main.go should now give different errors (eg, "imported and not used")

Set your GOPATH. Put your package foo source(s) in GOPATH/src/optional-whatever/foo/*.go and use it in code as

import "optional-whatever/foo"

You don't need to explicitly install foo, the go tool is a build tool, it will do that automagically for you whenever necessary.

也许,你可以将test.go文件放在与main.go相同的目录中,在test.go中,它使用如下内容:

import "./test"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM