Table of contents
Create your own project directory
Create pack1 package directory and source files
Create pack2 directory and source files
Create main package and source code files
This article is an example written by myself based on the narration of golang doc, read more doc without overturning https://go.dev/doc/
You can refer to How to Write Go Code - The Go Programming Language to understand the package module, path, directory related concepts in golang, and understand the Code organization of golang
The following is a simple example to illustrate how to create and import a local package. I have created two local packages here, pack1 and pack2 respectively. The example shows how to import it into your own project.
First look at the project structure, and then introduce it step by step
Create your own project directory
mkdir my_project && cd my_project
Create pack1 package directory and source files
Here I use two local packages pack1 and pack2 as an example
mkdir pack1 && cd pack1
vi pack1.go edit the source code file of pack1, and edit the following content
package pack1
import "fmt"
func HelloPack1() {
fmt.Println("Hello This Pack1")
}
Create pack2 directory and source files
cd to the project directory
mkdir pack2 && cd pack2
vi pack2.go edit the source code file of pack2, and edit the following content
package pack2
import "fmt"
func HelloPack2() {
fmt.Println("Hello This Pack2")
}
Create main package and source code files
cd to the project directory, vi main.go edit the source code file main.go of the main package, edit the following content
package main
import (
"fmt"
"my_project/pack1"
"my_project/pack2"
)
func main() {
fmt.Println("Hello This main")
pack1.HelloPack1()
pack2.HelloPack2()
}
Create a module my_project in the project directory
go mod init my_project
example validation
Run the project after creating the module
go run main.go