包是结构化代码的一种方式:每个程序都由包(通常简称为 pkg)的概念组成,可以使用自身的包或者从其它包中导入内容。
所有的包名都应该使用小写字母。
一个包可以由许多以 .go 为扩展名的源文件组成,因此文件名和包名一般来说都是不相同的。
你必须在源文件中非注释的第一行指明这个文件属于哪个包,如:package main。package main表示一个可独立执行的程序,每个 Go 应用程序都包含一个名为 main 的包。

1、标准库

在 Go 的安装文件里包含了一些可以直接使用的包,即标准库。
在 Windows 下,标准库的位置在 Go 根目录下的子目录 pkg\windows386 中;在 Linux 下,标准库在 Go 根目录下的子目录 pkg\linux_amd64 中(如果是安装的是 32 位,则在 linux_386 目录中)。一般情况下,标准包会存放在 $GOROOT/pkg/$GOOS$GOARCH/ 目录下。

序号 导入路径 简介
1 archive
2 archive/tar Package tar implements access to tar archives.
3 archive/zip Package zip provides support for reading and writing ZIP archives.
4 bufio Package bufio implements buffered I/O.
5 builtin Package builtin provides documentation for Go’s predeclared identifiers.
6 bytes Package bytes implements functions for the manipulation of byte slices.
7 compress
8 compress/bzip2 Package bzip2 implements bzip2 decompression.
9 compress/flate Package flate implements the DEFLATE compressed data format, described in RFC 1951.
10 compress/gzip Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.
11 compress/lzw Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T.
12 compress/zlib Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.
13 container
14 container/heap Package heap provides heap operations for any type that implements heap.Interface.
15 container/list Package list implements a doubly linked list.
16 container/ring Package ring implements operations on circular lists.
17 context Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
18 crypto Package crypto collects common cryptographic constants.
19 crypto/aes Package aes implements AES encryption (formerly Rijndael), as defined in U.S.
20 crypto/cipher Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
21 crypto/des Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S.
22 crypto/dsa Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
23 crypto/ecdsa Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.
24 crypto/ed25519 Package ed25519 implements the Ed25519 signature algorithm.
25 crypto/ed25519/internal
26 crypto/ed25519/internal/edwards25519
27 crypto/elliptic Package elliptic implements several standard elliptic curves over prime fields.
28 crypto/hmac Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S.
29 crypto/internal
30 crypto/internal/cipherhw Package cipherhw exposes common functions for detecting whether hardware support for certain ciphers and authenticators is present.
31 crypto/internal/randutil Package randutil contains internal randomness utilities for various crypto packages.
32 crypto/internal/subtle Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
33 crypto/md5 Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
34 crypto/rand Package rand implements a cryptographically secure random number generator.
35 crypto/rc4 Package rc4 implements RC4 encryption, as defined in Bruce Schneier’s Applied Cryptography.
36 crypto/rsa Package rsa implements RSA encryption as specified in PKCS#1 and RFC 8017.
37 crypto/sha1 Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
38 crypto/sha256 Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
39 crypto/sha512 Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
40 crypto/subtle Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
41 crypto/tls Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
42 crypto/x509 Package x509 parses X.509-encoded keys and certificates.
43 crypto/x509/pkix Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
44 database
45 database/sql Package sql provides a generic interface around SQL (or SQL-like) databases.
46 database/sql/driver Package driver defines interfaces to be implemented by database drivers as used by package sql.
47 debug
48 debug/dwarf Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf
49 debug/elf Package elf implements access to ELF object files.
50 debug/gosym Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.
51 debug/macho Package macho implements access to Mach-O object files.
52 debug/pe Package pe implements access to PE (Microsoft Windows Portable Executable) files.
53 debug/plan9obj Package plan9obj implements access to Plan 9 a.out object files.
54 encoding Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations.
55 encoding/ascii85 Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe’s PostScript and PDF document formats.
56 encoding/asn1 Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
57 encoding/base32 Package base32 implements base32 encoding as specified by RFC 4648.
58 encoding/base64 Package base64 implements base64 encoding as specified by RFC 4648.
59 encoding/binary Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
60 encoding/csv Package csv reads and writes comma-separated values (CSV) files.
61 encoding/gob Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver).
62 encoding/hex Package hex implements hexadecimal encoding and decoding.
63 encoding/json Package json implements encoding and decoding of JSON as defined in RFC 7159.
64 encoding/pem Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail.
65 encoding/xml Package xml implements a simple XML 1.0 parser that understands XML name spaces.
66 errors Package errors implements functions to manipulate errors.
67 expvar Package expvar provides a standardized interface to public variables, such as operation counters in servers.
68 flag Package flag implements command-line flag parsing.
69 fmt Package fmt implements formatted I/O with functions analogous to C’s printf and scanf.
70 go
71 go/ast Package ast declares the types used to represent syntax trees for Go packages.
72 go/build Package build gathers information about Go packages.
73 go/constant Package constant implements Values representing untyped Go constants and their corresponding operations.
74 go/doc Package doc extracts source code documentation from a Go AST.
75 go/format Package format implements standard formatting of Go source.
76 go/importer Package importer provides access to export data importers.
77 go/internal
78 go/internal/gccgoimporter Package gccgoimporter implements Import for gccgo-generated object files.
79 go/internal/gcimporter Package gcimporter implements Import for gc-generated object files.
80 go/internal/srcimporter Package srcimporter implements importing directly from source files rather than installed packages.
81 go/parser Package parser implements a parser for Go source files.
82 go/printer Package printer implements printing of AST nodes.
83 go/scanner Package scanner implements a scanner for Go source text.
84 go/token Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).
85 go/types Package types declares the data types and implements the algorithms for type-checking of Go packages.
86 hash Package hash provides interfaces for hash functions.
87 hash/adler32 Package adler32 implements the Adler-32 checksum.
88 hash/crc32 Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum.
89 hash/crc64 Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
90 hash/fnv Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo.
91 html Package html provides functions for escaping and unescaping HTML text.
92 html/template Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
93 image Package image implements a basic 2-D image library.
94 image/color Package color implements a basic color library.
95 image/color/palette Package palette provides standard color palettes.
96 image/draw Package draw provides image composition functions.
97 image/gif Package gif implements a GIF image decoder and encoder.
98 image/internal
99 image/internal/imageutil Package imageutil contains code shared by image-related packages.
100 image/jpeg Package jpeg implements a JPEG image decoder and encoder.
101 image/png Package png implements a PNG image decoder and encoder.
102 index
103 index/suffixarray Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.
104 internal
105 internal/bytealg
106 internal/cfg Package cfg holds configuration shared by the Go command and internal/testenv.
107 internal/cpu Package cpu implements processor feature detection used by the Go standard library.
108 internal/fmtsort Package fmtsort provides a general stable ordering mechanism for maps, on behalf of the fmt and text/template packages.
109 internal/goroot
110 internal/goversion
111 internal/lazyregexp Package lazyregexp is a thin wrapper over regexp, allowing the use of global regexp variables without forcing them to be compiled at init.
112 internal/lazytemplate Package lazytemplate is a thin wrapper over text/template, allowing the use of global template variables without forcing them to be parsed at init.
113 internal/nettrace Package nettrace contains internal hooks for tracing activity in the net package.
114 internal/oserror Package oserror defines errors values used in the os package.
115 internal/poll Package poll supports non-blocking I/O on file descriptors with polling.
116 internal/race Package race contains helper functions for manually instrumenting code for the race detector.
117 internal/reflectlite Package reflectlite implements lightweight version of reflect, not using any package except for “runtime” and “unsafe”.
118 internal/singleflight Package singleflight provides a duplicate function call suppression mechanism.
119 internal/syscall
120 internal/syscall/unix
121 internal/syscall/windows
122 internal/syscall/windows/registry Package registry provides access to the Windows registry.
123 internal/syscall/windows/sysdll Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
124 internal/testenv Package testenv provides information about what functionality is available in different testing environments run by the Go team.
125 internal/testlog Package testlog provides a back-channel communication path between tests and package os, so that cmd/go can see which environment variables and files a test consults.
126 internal/trace
127 internal/xcoff Package xcoff implements access to XCOFF (Extended Common Object File Format) files.
128 io Package io provides basic interfaces to I/O primitives.
129 io/ioutil Package ioutil implements some I/O utility functions.
130 log Package log implements a simple logging package.
131 log/syslog Package syslog provides a simple interface to the system log service.
132 math Package math provides basic constants and mathematical functions.
133 math/big Package big implements arbitrary-precision arithmetic (big numbers).
134 math/bits Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
135 math/cmplx Package cmplx provides basic constants and mathematical functions for complex numbers.
136 math/rand Package rand implements pseudo-random number generators.
137 mime Package mime implements parts of the MIME spec.
138 mime/multipart Package multipart implements MIME multipart parsing, as defined in RFC 2046.
139 mime/quotedprintable Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.
140 net Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
141 net/http Package http provides HTTP client and server implementations.
142 net/http/cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
143 net/http/cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
144 net/http/fcgi Package fcgi implements the FastCGI protocol.
145 net/http/httptest Package httptest provides utilities for HTTP testing.
146 net/http/httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
147 net/http/httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
148 net/http/internal Package internal contains HTTP internals shared by net/http and net/http/httputil.
149 net/http/pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
150 net/internal
151 net/internal/socktest Package socktest provides utilities for socket testing.
152 net/mail Package mail implements parsing of mail messages.
153 net/rpc Package rpc provides access to the exported methods of an object across a network or other I/O connection.
154 net/rpc/jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
155 net/smtp Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
156 net/textproto Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
157 net/url Package url parses URLs and implements query escaping.
158 os Package os provides a platform-independent interface to operating system functionality.
159 os/exec Package exec runs external commands.
160 os/signal Package signal implements access to incoming signals.
161 os/user Package user allows user account lookups by name or id.
162 path Package path implements utility routines for manipulating slash-separated paths.
163 path/filepath Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
164 plugin Package plugin implements loading and symbol resolution of Go plugins.
165 reflect Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
166 regexp Package regexp implements regular expression search.
167 regexp/syntax Package syntax parses regular expressions into parse trees and compiles parse trees into programs.
168 runtime Package runtime contains operations that interact with Go’s runtime system, such as functions to control goroutines.
169 runtime/cgo Package cgo contains runtime support for code generated by the cgo tool.
170 runtime/debug Package debug contains facilities for programs to debug themselves while they are running.
171 runtime/internal
172 runtime/internal/atomic
173 runtime/internal/math
174 runtime/internal/sys package sys contains system- and configuration- and architecture-specific constants used by the runtime.
175 runtime/pprof Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.
176 runtime/race Package race implements data race detection logic.
177 runtime/trace Package trace contains facilities for programs to generate traces for the Go execution tracer.
178 sort Package sort provides primitives for sorting slices and user-defined collections.
179 strconv Package strconv implements conversions to and from string representations of basic data types.
180 strings Package strings implements simple functions to manipulate UTF-8 encoded strings.
181 sync Package sync provides basic synchronization primitives such as mutual exclusion locks.
182 sync/atomic Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.
183 syscall Package syscall contains an interface to the low-level operating system primitives.
184 testing Package testing provides support for automated testing of Go packages.
185 testing/iotest Package iotest implements Readers and Writers useful mainly for testing.
186 testing/quick Package quick implements utility functions to help with black box testing.
187 text
188 text/scanner Package scanner provides a scanner and tokenizer for UTF-8-encoded text.
189 text/tabwriter Package tabwriter implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text.
190 text/template Package template implements data-driven templates for generating textual output.
191 text/template/parse Package parse builds parse trees for templates as defined by text/template and html/template.
192 time Package time provides functionality for measuring and displaying time.
193 unicode Package unicode provides data and functions to test some properties of Unicode code points.
194 unicode/utf16 Package utf16 implements encoding and decoding of UTF-16 sequences.
195 unicode/utf8 Package utf8 implements functions and constants to support text encoded in UTF-8.
196 unsafe Package unsafe contains operations that step around the type safety of Go programs.

2、导入包

2.1、项目创建到任意目录

目录不在GOROOT/src或GOPATH/src下。

  1. //导入同一个项目里面包
  2. //格式一 import "包的路径或 URL 地址"
  3. import "fmt"
  4. import "../pack1/pack1"
  5. //格式二 import ("包的路径或 URL 地址")
  6. import (
  7. "fmt"
  8. "../pack1/pack1"
  9. )

2.2、项目创建到GOROOT/src或GOPATH/src下

  1. //导入同一个项目里面包
  2. //格式一 import "项目名称/包名"
  3. import "fmt"
  4. import "demo/pack1/pack1"
  5. //格式二 import ("包的路径或 URL 地址")
  6. import (
  7. "fmt"
  8. "demo/pack1/pack1"
  9. )

2.3、别名

  1. //格式一 使用.作为别名,可以不使用包名,直接使用包中的函数
  2. import . "./pack1"
  3. //格式二 使用_作为别名,不可以使用包下的函数,只执行包下的init函数
  4. import _ "./pack1"
  5. //格式三 使用名称作为别名,可以使用名称代替包名访问包中的函数
  6. import alias "./pack1"