SoFunction
Updated on 2025-04-11

Two ways to introduce custom packages to golang

For example, install go jdk on D disk D:\golang\bin

It is recommended to place the project in the D:\golang\src directory. At this time, you can directly read the GOPATH to D:\golang\src. At this time, you can introduce a custom package path, that is, your project name + specific package path

1. The first stupid way: for example, you can build a project under D:\golang\src my-project

The my-project directory level is as follows:

  • main/
  • utils/

Call the method GetSum of the custom package utils package

package main

import (
	"fmt"
	"my-project/utils"
)

func main() {
	var result int = (100, 200)
	(result)
}

You can customize the package name and function GetSum under the package

package utils

func GetSum(a int, b int) int {
	return a + b
}

2. The second way of use, the project is recommended

As early as the terminal, enter the command: go mod init and usually follow the git project path.

After executing the go mod init /golang/go-web command, the file is roughly as follows. The following is just a virtual personal git project address, which depends on the individual project situation:

module /golang/go-web
go 1.20

Import package test
Create a new testModule/

package testModule

func CountSum(a int, b int) int {
	return a + b
}

Introduce package test in entry file

package main

import (
	"fmt"
	"/golang/go-web/testModule"
)
func main () {
		res := (23, 88)
		("Input calculation result:", res)
}

This is the end of this article about two methods of introducing custom packages to golang. For more related contents of introducing custom packages to golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!