初识 Golang 之安装运行篇

在这个网站我们算是初次尝试 Golang 以及初识其语法,不得不说,Go Playground 确实是一个熟悉 Golang 的很好的平台,但是在线平台的实际用途还是有限的。例如,你不能使用它来处理文件。它也没有办法从终端获得用户的输入。
安装步骤
访问https://golang.org/。选择适合你操作系统和版本的安装包,下载到本地。我下的是 windows 版本的,一路下一步默认安装到 C 盘。



打开一个新的终端或者命令提示窗口。检查 go 是否安装成功。

代码编译
计算机实际上是不能直接运行 Go 代码的。在此之前,需要获取源代码文件并进行编译:将其转换为 CPU 可以执行的二进制格式。
源代码 -> hello.go -> Compile -> 编译后的代码:Executable file -> 计算机执行目标文件
下面,我们在本地用 Go 来编译和运行一个“hello world”的例子。
首先,新建一个 go 文件,将代码保存到文件中


之后,在 hello.go 文件的目录下打开一个新的终端或者命令提示窗口。运行 go fmt hello.go 来整理代码格式(这一步不是必需的,但,是一个好习惯)

运行 go build hello.go 编译源代码。这将向当前目录添加一个可执行文件。在 windows 上,可执行文件被命名为 hello.exe。


运行可执行文件。在 Windows 环境中,只需输入 hello.exe 即可。

到此,Go 的下载、安装、编译、执行一系列步骤已完成。人生苦短,我要换 Go。
小彩蛋
go run 命令编译并运行源文件,而不将可执行文件保存到当前目录。它非常适合快速尝试简单的程序。
下面,让我们一起来看看这个彩蛋的颜值吧~


能立即看到程序输出。如果对源代码进行更改,在不执行单独的编译步骤时,只需使用 go run 运行代码,即可立即看到结果。当在处理小程序时,go run 灰常方便!
版权声明: 本文为 InfoQ 作者【Kylin】的原创文章。
原文链接:【http://xie.infoq.cn/article/cb8ddb54a6fb60dab580b4845】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
评论