白話Golang的Hello world

####安裝Golang開發環境 要想使用go語法作開發,首先固然是要搭建go的開發環境了。到Golang官網上下載go的安裝包,找本身機器對應的版本。 固然若是你是在天朝,一般狀況下被牆是不可避免的,你能夠自行翻越或者到Golang中國上下載。 go在大中華地區仍是很流行的,可能跟圍棋是中國發明的有關。git

下載後找個順眼的地方解壓,好比/usr/local/go。進去到bin目錄下執行go命令會獲得以下信息:github

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 [command]" for more information about a command.

Additional help topics:

	c           calling between Go and C
	buildmode   description of build modes
	filetype    file types
	gopath      GOPATH environment variable
	environment environment variables
	importpath  import path syntax
	packages    description of package lists
	testflag    description of testing flags
	testfunc    description of testing functions

Use "go help [topic]" for more information about that topic.

諾,go開發環境你就按照好了,夠傻瓜吧。golang

然而,這還不夠。你通常會有一個本身寫那些弱智代碼的地方,稱之爲工做目錄吧。在工做目錄下怎麼使用go呢? 這就須要把go這個命令放進環境變量,爲了能完整的使用go來開發。咱們須要定義一個GOROOT的環境變量,並將剛纔這個bin目錄放進path從而在任何地方都能使用go命令。 Linux下大概相似下面這樣:vim

# vim /etc/profile

export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin

# source /etc/profile

這樣你就能夠隨心所欲地使用go這個命令了。工具

####指定GOPATH 不過,這還沒完。go這麼拽的語言固然要有點拽的姿式。除了GOROOT,還要定義一個GOPATH的環境變量,用來指定go項目源碼和二進制文件的目錄。 假設如此定義:ui

# vim /etc/profile

export $GOPATH=/workspace/golang:/data/go

# source /etc/profile

這裏咱們指定了兩個GOPATH,/workspace/golang和/data/go,這樣你就能夠在GOPATH下執行相似spa

go get github.com/tools/godep

這樣的命令來獲取一個網上go開源項目了。上面的命令是獲取godep這個包管理工具的源碼並安裝到GOPATH的bin目錄下。code

####Go項目目錄結構 GOPATH下的目錄結構一般爲:orm

|--bin
|--pkg
|--src

bin存放編譯後的可執行文件,pkg存放編譯過程使用的包文件,src存放項目源文件。bin和pkg目錄go會自動建立。ip

####Hello world 至此,咱們能夠操手來個hello world體味一下。在GOPATH的src目錄下建立main.go文件:

package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

代碼格式自動格式化一下

go fmt main.go

哎呦,很叼噢,有木有!運行一下

go run main.go

世界都光明瞭。。。

####References The Go Programming Language

GOPATH 深度解析

相關文章
相關標籤/搜索