14

Golang 包和依赖管理

 4 years ago
source link: https://studygolang.com/articles/27056
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
  1. package是基本复用模块单元。

注:以首字母大小写来区分是否可被包外代码访问。大写代表,可以被包外引入。

小写代表,不可被包外引入。

  1. package名可以与目录名不一致。(但建议一致)

  2. 同一目录下的Go文件,必须属于同一个package。

PS:在终端下,输入 go env ,可获得go的环境信息。

操作步骤:

  • 第一步:我们要配置 GoPath 。将我们的工程路径写入 GoPath 内。

打开终端并输入:

vim ~/.bash_profile
复制代码

配置 GoPath ,例如:

export GOPATH="/Users/Liu/go:/Users/Liu/Documents/VSCode/go_learning"
export PATH="$HOME/.Liu/bin:$PATH"
复制代码
  • 第二步:编写包依赖代码

首先,创建一个 series 包,作为一个会被外部引用的 package

package series

// 小写开头square,只能在当前package内部使用
func square(n int) int {
	return n * n
}

// 大写开头Square,可以被此package外部引入使用
func Square(n int) int {
	return n * n
}
复制代码

再编写一个测试 package ,叫 client

package client

import (
	"ch15/series"
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log("result =", series.Square(2)) // 大写开头Square,可以引入使用
	// t.Log(series.square(2)) // 小写开头找不到
}
复制代码

这时就会发现,大写字母开头的方法是可以被引入的( public )。 而小写字母开头的方法是不会被引入的( private )。

二、依赖管理工具

这里,我们演示一下glide的基本用法:

  • 第一步:安装glide:
brew install glide
复制代码
  • 第二步:进入项目目录,初始化glide:
glide init
复制代码

这时候,目录下会出现一个 glide.yaml 文件。

vim glide.yaml
复制代码

修改如下:

package: ch15/remote_package
import: []
testImport:
- package: github.com/easierway/concurrent_map
  version: 0.9.1
复制代码

打开终端,执行: glide install

aMFf2eY.jpg!web

这时候,目录下会出现vendor文件夹,用来存放我们需要的库。

  • 第三步:import导入并使用
package remote_package_test

import (
	"testing"

	cm "github.com/easierway/concurrent_map"
)

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK