How to use custom packages
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 )
GO_Directory //the one assigned to $GOPATH
__MyProject
_____ main.go
_____ Entites
_____ Fiboo // in my case, fiboo is a database name
_________ Client.go // in my case, Client is a table name
On File MyProject\Entities\Fiboo\Client.go
package Fiboo
type Client struct{
ID int
name string
}
on file MyProject\main.go
package main
import(
Fiboo "./Entity/Fiboo"
)
var TableClient Fiboo.Client
func main(){
TableClient.ID = 1
TableClient.name = 'Hugo'
// do your things here
}
( 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 !
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:
- 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.go
Now, in the top-level main.go
, you could import "myproject/mylib"
and it would work OK.
For this kind of folder structure:
main.go
mylib/
mylib.go
The simplest way is to use this:
import (
"./mylib"
)
For a project hosted on GitHub, here's what people usually do:
github.com/
laike9m/
myproject/
mylib/
mylib.go
...
main.go
mylib.go
package mylib
...
main.go
import "github.com/laike9m/myproject/mylib"
...