Official website tutorial (need to turn over the wall) : tour.go-zh.org/basics/1

package

Each Go program is made up of packages.

The program starts from the main package.

Use both packages by importing paths “FMT” and” Math/RAND “.

By convention, the package name is the same as the last element of the import path. For example, the source code in the “Math/RAND” package starts with a Package RAND statement.

The sample

package main

import (
	"fmt"
	"math/rand"
)

func main(a) {
    // Translated from official documentation
    // rd.intn (n int) returns a number of type int.
    // The number must be a non-negative pseudo-random number between [0,n]. The condition for the method argument n is that n <= 0 is not allowed.
    // Specific link: https://go-zh.org/pkg/math/rand/#Intn
    fmt.Println("My favorite number is", rand.Intn(10))}Copy the code




The import

example

import (
    "fmt"
    "math"
)
Copy the code

This code combines the imports with parentheses, which are “grouped” import statements.

Of course, you can also write multiple import statements, for example:

import "fmt"
import "math"
Copy the code

These are equivalent. A better form is to use grouped import statements.

The export of

example

package main

import (
    "fmt"
    "math"
)

func main(a) {
    fmt.Println(math.pi)
}
Copy the code

In Go, if a name begins with a capital letter, it is exported. For example, Pizza is an exported name, as is Pi, which is exported from the Math package.

Pizza and PI do not begin with a capital letter, so they are unexported.

When importing a package, you can reference only the exported names in it. Any “not exported” names are not accessible outside the package.

Execute the code and observe the error output.

Error:

prog.go:9:14: cannot refer to unexported name math.pi
prog.go:9:14: undefined: math.pi

Program exited.
Copy the code

Rename math. PI to math. PI and it will work. Because Pi is the exported name.