如同許多的Script語言一樣,Golang也是有許多可以在Terminal上操作的指令,因此在開始Hello World!之前先介紹一些常用的指令給大家知道
在Terminal上執行go指令就會看到一系列的指令介紹
$ go
Go is a tool for managing Go source code.
Usage:
go command [arguments]
The commands are:
build compile packages and dependencies
clean remove object files
doc show documentation for package or symbol
env print Go environment information
fix run go tool fix on packages
fmt run gofmt on package sources
generate generate Go files by processing source
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet run go tool vet on packages
...略...
Use "go help [topic]" for more information about that topic.
如果對於某個指令特別需要幫助可以用go help [topic]指令
其中要特別介紹的有四個指令go run, go build, go install, go clean
直接執行golang code:
$ go run src/helloWorld/main.go
Hello World!
buil,如果沒有錯誤就產生執行檔於當前目錄
$ ls
main.go
$ go build
$ ls
main.go helloWorld
build後多的helloWorld檔案即是執行檔
如果沒有錯誤則產生執行檔於$GOPATH/bin
$ ls
main.go
$ go install
$ ls
main.go
$ ls $GOPATH/bin
helloWorld
執行後會將build產生的檔案都刪除(install的不會刪)
$ go build
$ ls
main.go helloWorld
$ go clean
$ ls
main.go
在這邊會推薦使用文字編輯器(Sublime, Vim等)或是IDE(WebStorm之類的)來寫code
編輯$GOPATH/helloWorld/main.go
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
}
之後在$GOPATH/helloWorldd的目錄中執行go run main.go
$ go run main.go
Hello World!
這樣就代表你成功啦!