Preamble: This article takes a brief look at golang’s package management.

(Note: This article is out of date and now uses the official Go mod to manage dependencies. Read carefully.)

A package,

  1. Package is the basic reusable module unit.

Note: Use uppercase to distinguish whether it is accessible by code outside the package.

Capital letters, can be imported from outside the package. Lowercase indicates that it cannot be imported from outside the package.

  1. Package names can be inconsistent with directory names. (But the advice is consistent)

  2. Go files in the same directory must belong to the same package.

PS: Run the go env command to obtain the GO environment information.

Operation steps:

  • Step 1: We need to configureGoPath. Write our project path toGoPathInside.

Open terminal and type:

vim ~/.bash_profile
Copy the code

Configure GoPath, for example:

export GOPATH="/Users/Liu/go:/Users/Liu/Documents/VSCode/go_learning"
export PATH="$HOME/.Liu/bin:$PATH"
Copy the code
  • Step 2: Write package-dependent code

First, create a Series package as a package that will be referenced externally.

package series

// Square begins with lowercase, which can only be used inside the current package
func square(n int) int {
	return n * n
}

// Square, which can be used outside of this package
func Square(n int) int {
	return n * n
}
Copy the code

Write another test package called client.

package client

import (
	"ch15/series"
	"testing"
)

func TestPackage(t *testing.T) {
	t.Log("result =", series.Square(2)) // start with a capital Square
	// t.log (series. Square (2)
}
Copy the code

In this case, you will find that the method of starting with a capital letter can be introduced (public). Lower-case methods will not be introduced (private).

Second, dependency management tools

  • Dep: github.com/golang/dep (…
  • Glide:github.com/Masterminds…
  • Godep:github.com/tools/godep…

Here, we demonstrate the basic use of Glide:

  • Step 1: Install Glide:
brew install glide
Copy the code
  • Step 2: Enter the project directory and initialize Glide:
glide init
Copy the code

A Glide. Yaml file appears in the directory.

vim glide.yaml
Copy the code

Modified as follows:

package: ch15/remote_package
import: []
testImport:
- package: github.com/easierway/concurrent_map
  version: 0.9.1
Copy the code

Start the terminal and run Glide Install

At this point, the vendor folder will appear under the directory to store the libraries we need.

  • Step 3: import Import and use
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")))}Copy the code