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
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 package
I'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?
package lexico
En la clase package main
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
go get
-table project.If your library is for internal use, you could go like this:
To demonstrate:
Now, in the top-level
main.go
, you couldimport "myproject/mylib"
and it would work OK.another solution:
add
src/myproject
to $GOPATH.Then
import "mylib"
will compile.For this kind of folder structure:
The simplest way is to use this:
For a project hosted on GitHub, here's what people usually do:
mylib.go
main.go
I am an experienced programmer, but, quite new into Go world ! And I confess I've faced few difficulties to understand Go... I faced this same problem when trying to organize my go files in sub-folders. The way I did it :
GO_Directory ( the one assigned to $GOPATH )
On File MyProject\Entities\Fiboo\Client.go
on file MyProject\main.go
( I am running Go 1.9 on Ubuntu 16.04 )
And remember guys, I am newbie on Go. If what I am doing is bad practice, let me know !