本文最初发表在我的个人博客,欢迎查看原文:
blog.favorstack.io/golang
简介
官方是这样介绍Go的:
Go是一种开源编程语言,可以轻松构建简单、可靠、高效的软件。
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
官网(墙外): https://golang.org/
开发平台支持:Linux, macOS, Win等等
如大多数语言一样,GO需要先配置开发环境
发布策略
Go大约每6个月发布一次大版本,每个大版本都会支持到新的2个大版本发布后,比如当前的大版本为1.12
,会一直提供支持,直到1.14
发布。期间只修复严重问题,当然包括严重的安全问题,以次要的修订版形式发布,如现在的最新版1.12.1
即为一个修订版。
下载
下载地址:https://golang.org/dl/
本教程使用的版本为:go1.12
目前最新版本为
1.12.1
(released 2019/03/14)
Go主要提供了压缩包和可执行程序格式的安装包,选择一个下载即可。
go1.12
File Name | SHA256 Checksum |
---|---|
go1.12.darwin-amd64.pkg | 71ff572e16426eb2205748aec270ce819beb0fc740998e0443629f8357c60353 |
go1.12.linux-amd64.tar.gz | 750a07fef8579ae4839458701f4df690e0b20b8bcce33b437e4df89c451b6f13 |
go1.12.windows-amd64.msi | 13515401fc5e8e2959ee37413f9d2af934e2bfbba87a2a4d7a1c6058a9dbe6d5 |
go1.12.src.tar.gz | 09c43d3336743866f2985f566db0520b36f4992aea2b4b2fd9f52f17049e88f2 |
安装
系统要求
Operating system | Architectures | Notes |
---|---|---|
FreeBSD 10.3 or later | amd64, 386 | Debian GNU/kFreeBSD not supported |
Linux 2.6.23 or later with glibc | amd64, 386, arm, arm64,s390x, ppc64le | CentOS/RHEL 5.x not supported. Install from source for other libc. |
macOS 10.10 or later | amd64 | use the clang or gcc† that comes with Xcode‡ for cgo support |
Windows 7, Server 2008R2 or later | amd64, 386 | use MinGW gcc†. No need for cygwin or msys. |
†A C compiler is required only if you plan to use cgo.
‡You only need to install the command line tools for Xcode. If you have already installed Xcode 4.3+, you can install it from the Components tab of the Downloads preferences panel.
安装及配置
如果之前安装过老版本的,需要先将老版本目录删除。
Linux下:
tarball压缩包的解压到任意位置即可,如:
$ tar -zxvf go1.12.linux-amd64.tar.gz -C /usr/local
记得将可执行程序路径添加到环境变量,一般是~/.bashrc
或者~/.profile
:
export PATH=$PATH:/usr/local/go/bin
要在当前窗口生效,执行. ~/.bashrc
或source ~/.bashrc
。
macOS下:
macOS安装包默认安装在/usr/local/go
,相应的会添加/usr/local/go/bin
到环境变量中,它是自动创建了一个/etc/paths.d/go
文件,其中内容为
/usr/local/go/bin
Windows下:
Win的MSI安装包默认安装在c:\Go
,相应的会添加c:\Go\bin
到环境变量中;如果是手动配置的,到系统环境变量中添加即可(跟java配置一样)。
检查
检查版本
$ go version
go version go1.12 darwin/amd64
第一个程序,国际惯例:
首先创建工作空间:
# 如果你不想使用这个默认目录,请参考下一篇文章[二 概念篇:如何写Go代码]
$ mkdir $HOME/go && cd !$
接着创建src/hello
,并在里面创建一个hello.go的文件:
$ mkdir -p src/hello && cd !$
$ vi hello.go
在hello.go中输入以下内容并保存退出:
package main
import "fmt"
func main() {
fmt.Printf("hello, world!\n")
}
然后构建编译:
$ go build
正常的话,会在当前目录下生成名为hello
的可执行程序,然后我们可以执行:
$ ./hello
hello world!
安装没问题的话,应该就能看到上边的输出内容了。
你还可以执行go install
将可执行文件安装到workspace下的bin目录,或者go clean -i
清除已编译好的程序。
如果将工作空间的bin
目录也加入到环境变量的话,就可以直接全局执行hello命令了:
$ hello
hello world!
如何卸载
首先直接将安装目录删除。例如Linux,macOS,FreeBSD的/usr/local/go
,或者Windows的c:\Go
。
然后需要Go的bin目录从环境变量移除。Linux和FreeBSD一般是在~/.bashrc
或 $HOME/.profile
,或者系统范围的配置/etc/profile
;macOS安装包安装的一般会在/etc/paths.d/go
文件中;Windows则在系统设置中的环境变量内。
环境变量的位置可以参考上述
安装及配置
一节