[go学习笔记]十八、构建可复用的模块

759 阅读2分钟

package

  • 基本服用模块单元 ** 以首字母大写来表明可被包外代码访问
  • 代码的 package 可以和所在的目录不一致
  • 统一目录里的 Go 代码的 package 要保持一致

首先需要先把代码路径添加到GOPATH里边

sudo vim ~/.base_profile

然后找到GOPATH

 export GOPATH=$HOME/go:$HOME/Code/golearning

说明一下:$HOME 代表的是 用户主目录,例如:/Users/用户名/

不明白的话也可以尝试着执行

cd $HOME

配置好了以后,esc 键,然后 :wq 保存

这个时候我们就可以在代码里边引用本地的 package 了

在引用过程中,需要被引用的方法名称首字母必须大写否则不能被引用

my_series.go

package series

func square(n int) int {
	return n * n
}

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

client1_test.go

package client1_test

import (
	"ch15/series"
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log(series.GetFibonacci(10))
	t.Log(series.square(5))
}

输出

# ch15/client_test [ch15/client.test]
./package_test.go:10:8: cannot refer to unexported name series.square   <-这里提示不能使用没有被允许的series.square
./package_test.go:10:8: undefined: series.square

Compilation finished with exit code 2

那看一下修正后的代码 修正后的 my_series.go

package series

func Square(n int) int {
	return n * n
}

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

修正后的 client1_test.go

package client1_test

import (
	"ch15/series"
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log(series.GetFibonacci(10))
	t.Log(series.Square(5))
}

输出

=== RUN   TestPackage
--- PASS: TestPackage (0.00s)
    package_test.go:9: [1 1 2 3 5 8 13 21 34 55]
    package_test.go:10: 25
PASS

Process finished with exit code 0

init 方法

  • 在 main 被执行前,所有依赖的 package 的 init 方法都会被执行
  • 不同包的 init 函数按照包倒入的依赖关系界定执行顺序
  • 每个包可以由多个 init 函数
  • 包的每个源文件也可以有多个 init 函数,这点比较特殊

示例代码

package series

import "fmt"

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

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

func Square(n int) int {
	return n * n
}

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

import (
	"ch15/series"
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log(series.GetFibonacci(10))
	t.Log(series.Square(5))
}

输出

init1
init2
=== RUN   TestPackage
--- PASS: TestPackage (0.00s)
    package_test.go:9: [1 1 2 3 5 8 13 21 34 55]
    package_test.go:10: 25
PASS

Process finished with exit code 0

虽然我调用了两个不同的函数但是init都只执行了一边

remote package

  1. 通过 go get 来获取远程依赖
  • go get -u 强制从网络更新远程依赖
  1. 注意代码在 GitHub 上的组织形式,以适应 go get
  • 直接以代码路径开始,不要有src
package remote

import (
	cm "github.com/easierway/concurrent_map"
	"testing"
)

func TestConcurrentMap(t *testing.T)  {
	m:=cm.CreateConcurrentMap(99)
	m.Set(cm.StrKey("key"),10)
	t.Log(m.Get(cm.StrKey("key")))
}

输出

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

Process finished with exit code 0