SoFunction
Updated on 2025-03-01

How to introduce custom packages to goLang

After reading the basic syntax of golang, I tried golang's package management for modular programming, but I really fell into a few pitfalls. Let's summarize it.

1. Set $GOPATH environment variable

Golang is different from C or php. It will not automatically find files under the current path. You must first add the path of your own project in $GOAPTH;

2. The first letter of the API function provided to the outside of the custom package must be capitalized.

For example: func api() string {return "hello api!"} cannot be detected by out-of-package functions;

Should be changed to: func Api() string {return "hello api!"}

3. Compilation and installation of packages

The packaged .go files must be stored in a separate folder (such as test).

Then use the go build and go install commands for the test folder: then add the generated pkg folder under $GOPATH, and the file will be generated under the folder (so, the parent folder name of the package file is the same as the package name in the end)

4. Use of packages

The name of the generated package may be inconsistent with the real name of the package;

For example, the directory structure is as follows:

project
 >src
  >test
    >
 
 >pkg
  >XXXXXX
    >

The code is as follows:

package my

func Test() string{ return ""}

The code is as follows:

package my
import(
  "fmt"
  "test"
)

func main(){
  (()); //It can be seen that the use of "my" and import "test" are inconsistent;}

The above method of introducing custom packages to goLang is all the content I share with you. I hope you can give you a reference and I hope you can support me more.