這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">學習一下Go語言。學習之前,首先要搭建一下Go語言的開發環境,這篇文章主要介紹一下搭建環境的過程。</span>
一、安裝Go語言依賴包
Go語言部分功能是用C語言開發的,所以安裝Go之前需要安裝gcc,make等依賴,ubuntu下的安裝命令如下:
sudo apt-get install bison ed gawk gcc libc6-dev make
二、擷取Go源碼
成功安裝了Go語言的依賴之後,就需要下載Go語言的源碼包,方法比較多:可以通過hg拷貝源碼,也可以到官網上直接下載對應的源碼包
1、使用hg拷貝
這種方式需要先安裝Mercurial,Mercurial是類似git的版本管理系統,簡稱hg(水銀),安裝命令如下:
sudo apt-get install python-dev sudo apt-get install build-essential sudo apt-get install mercurial
安裝完成之後,通過下面的命令拷貝代碼:
cd ~/ hg clone -r release https://go.googlecode.com/hg/ go
2、直接下載
Go語言官方下載地址:https://golang.org/dl/
由於被牆的原因,官方下載地址很難正常開啟,所以我將自己下載的Ubuntu 32位的源碼包放在了百度網盤上,安裝環境和我一樣的同學可以直接下載這個:http://pan.baidu.com/s/1jGuZBhk
下載之後將壓縮包解壓到HOME目錄下。
三、配置Go環境變數
在編譯安裝之前,還需要設定Go語言的環境變數,在Ubuntu下的配置方法如下:
1、開啟HOME目錄下的.bashrc檔案
vim ~/.bashrc
2、在檔案的最後添加以下內容
export GOBIN=$GOROOT/binexport GOARCH=386export GOOS=linuxexport PATH=$GOROOT/bin:$PATHexport GOPATH=$HOME/workspace/Go
3、儲存設定並運行命令使其生效
source ~/.bashrc
四、編譯Go源碼包
以上步驟完成之後就可以執行編譯指令碼了,編譯Go語言的命令如下:
cd $GOROOT/src./all.bash
編譯會執行大概60分鐘的時間,當你看到以下資訊的時候,就表示安裝成功了:
ALL TESTS PASSED ---Installed Go for linux/386 in /home/wuxianglong/go.Installed commands in /home/wuxianglong/go/bin.
五、Hello World!
在學習一門新的語言時,我們寫的第一行代碼一般是Hello World,這裡也不例外。在執行完上述的步驟之後,你可以在命令列輸入 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 env print Go environment information fix run go tool fix on packages fmt run gofmt on package sources 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 filetype file types gopath GOPATH environment variable 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.
之後,可以寫一個Hello World程式,代碼如下:
package main import "fmt" func main() { fmt.Printf("Hello World!\n")}
將上面的代碼儲存在檔案hello.go中,然後在命令列執行:
go run hello.go# 輸出結果:Hello World!
OK!Go語言的開發環境已經安裝成功了!
Go語言的vim高亮
Go語言內建vim 的文法高亮檔案。
將$GOSRC/misc/vim/目錄下檔案拷貝到~/.vim/目錄下(如果沒有該目錄則建立)
建立~/.vim/ftdetect/go.vim