15

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
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60

3 Answers3

11

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.

zzzz
  • 87,403
  • 16
  • 175
  • 139
  • 3
    To clarify: the package will be a directory (e.g. 'foo'). You will import the folder as the module, not the individual source files. – VOIDHand Jun 10 '12 at 04:18
  • This answer makes it clear that we need to restrict ourselves to put all packages in `$GOPATH`. I was confused until now. Here's a context - https://github.com/golang/dep/issues/1441 – roshnet Mar 08 '20 at 15:42
8

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")

William Pursell
  • 204,365
  • 48
  • 270
  • 300
-3

maybe, you can put the test.go file in the same directory with the main.go, and in test.go, it uses something like this:

import "./test"
splade
  • 11
  • 1