GoDistributed Learning Tool (16) -- Reusable package Construction in go

In this article, you will learn how to build your own package into a project in the go language and how to build a package from a remote (github) into a project.

1. Build a local package

  • Package is the basic unit of a reusable module and is implemented as a function in uppercase to indicate that it can be accessed by out-of-package code
  • The package of code can be inconsistent with the code in the path
  • Keep package s of Go code in the same directory consistent

Personally, understanding a local package is like a header file in C++/C. All other code needs to do is include the header file to use the functions of life in the header file.

When building your own Go language packages here, you need to be aware of the code path and create your own implemented packages directory under the src directory in the specified GOPATH path in your environment.

For example, specify ~/. In bashrc:

export GOPATH="~/go/"

Then create your own package directory in the src directory under this path, as in the series directory below

Implement series.go, and import "ch11/series" from the source files in other package directories to use series. Functions implemented in go

Ps: series. The function name implemented in go needs to be capitalized at the beginning so that it specifies that the current function can be called outside the package
Where series. The go implementation code is as follows:

package series

import "fmt"

// To get a Fibonacci column, the function name must be uppercase, and if lowercase, a syntax error will be reported in subsequent out-of-package calls
func GetFibList(n int) []int{
	if n < 2 {
		return nil
	}

	if n > 100 {
		return nil
	}

	fibList := []int{1,1}
	for i := 2; i < n; i++ {
		fibList = append(fibList, fibList[i-1] + fibList[i-2])
	}

	return fibList
}

Package_in ch11 directory Create a package_in the test directory Test. Go test code, calling functions in the series package

package package_test

import (
	fib "test/ch11/series" // My src directory is test/ch11/series
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log(fib.GetFibList(5))
}

The final run was successful with the following output:

=== RUN   TestPackage
    package_test.go:9: [1 1 2 3 5]
--- PASS: TestPackage (0.00s)

2. Initialize init method in package

GO supports the method of initializing packages, and this method has several interesting features

  • All dependent package init methods will be executed before main is executed
  • The init functions of different packages determine the execution order based on the dependencies of the package import
    For example, if pkg1 and pkg2 are packages, and the first package is import ed first, then the init function of pkg1 will execute first
  • Each package can have multiple init functions
  • Each source file of a package can also have multiple init functions

For example, in the previous series package, we were in series. Add two init functions to go

package series

import "fmt"

func init() {
	fmt.Println("first init")
}

func init() {
	fmt.Println("second init")
}

func GetFibList(n int) []int{ /* Two return values */
	if n < 2 {
		return nil
	}

	if n > 100 {
		return nil
	}

	fibList := []int{1,1}
	for i := 2; i < n; i++ {
		fibList = append(fibList, fibList[i-1] + fibList[i-2])
	}

	return fibList
}

Multiple init s are executed first when executed in the test file:

package package_test

import (
	"testing"
	fib "test/ch11/series"
)

func TestPackage(t *testing.T) {
	t.Log(fib.GetFibList(5))
}

The output is as follows, you can see that the init function takes precedence over all other callers when a method in the series is called

first init
second init
=== RUN   TestPackage
    package_test.go:9: [1 1 2 3 5]
--- PASS: TestPackage (0.00s)
PASS

The init function helps us initialize some resources in our package ahead of time

3. Build a remote package

Many times in our project, we need some open source go framework: distributed coordinating service etcd, distributed communication go-grpc, etc. These open source package packages are needed, so go language provides a convenient way to obtain them, similar to the following:

go get -u github.com/easierway/concurrent_map

The specified GitHub source path does not need to be added. Git, the above command will http://github.com/easierway/concurrent_map.git The master branch code in is put into the src/github of GOPATH. COM path, and does not include in the project. Git directory (not updated with the community).

Once included, the remote package can be used directly:

package remote_package

import "testing"
import cm "github.com/easierway/concurrent_map" //Import package downloaded remotely

func TestConcurrentMap(t *testing.T) {
        m := cm.CreateConcurrentMap(99) // Call related methods within the package
        m.Set(cm.StrKey("key"),10)
        t.Log(m.Get(cm.StrKey("key")))
}

The output is as follows:

=== RUN   TestConcurrentMap
    remote_package_test.go:9: 10 true
--- PASS: TestConcurrentMap (0.00s)
PASS

Tags: Programming

Posted by shana on Sun, 01 May 2022 23:18:48 +0300