snippetgoCritical
How to use custom packages
Viewed 0 times
howusepackagescustom
Problem
I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:
mylib.go
main.go
When I try to
I've tried to run
mylib.go
package mylib
type SomeType struct {
}main.go
package main
import (
"mylib"
)
func main() {
}When I try to
go run main.go, I get this error:main.go:4:2: import "mylib": cannot find packageI've tried to run
go build mylib.go first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?Solution
First, be sure to read and understand the "How to write Go code" document.
The actual answer depends on the nature of your "custom package".
If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate
If your library is for internal use, you could go like this:
To demonstrate:
Now, in the top-level
The actual answer depends on the nature of your "custom package".
If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate
go get-table project.If your library is for internal use, you could go like this:
- Place the directory with library files under the directory of your project.
- In the rest of your project, refer to the library using its path relative to the root of your workspace containing the project.
To demonstrate:
src/
myproject/
mylib/
mylib.go
...
main.goNow, in the top-level
main.go, you could import "myproject/mylib" and it would work OK.Code Snippets
src/
myproject/
mylib/
mylib.go
...
main.goContext
Stack Overflow Q#15049903, score: 191
Revisions (0)
No revisions yet.