編寫 Hello World
創建文件 hello.go,不寫入任何內容。按照如下的命令嘗試進行編譯
$ go run hello.go
將會打印出如下錯誤:
package main:
hello.go:1:1: expected 'package', found 'EOF'
在Go語言中,所有文件必須隸屬於某一個包。當前,只需要理解在文件的頭部聲明一個package name就可以了,其中package為關鍵字,name為你自己起的一個包名字。
在大型的程序中,包可以很好的有條理的組織各種功能。
例如,如果你想寫一個關於交通工具的虛擬模型,你應該把所有屬於car的模型放入一個叫做cars的包中,把所有屬於bus的模型放入buses的包中。
組織相關的功能只是包的一種用途。
現在讓我們在剛剛創建的hello.go文件中添加一條語句,之后重新執行運行命令
內容:
package main
執行后,會打印如下錯誤:
runtime.main_main·f: relocation target main.main not defined
runtime.main_main·f: undefined: "main.main"
Go程序啟動時,需要在文件中有一個可標識入口。就像汽車必須有一把啟動點火的鑰匙、電腦需要有一個開機鍵,Go程序中需要有一個main函數。
在hello.go文件中添加另外一行,並且重試
內容:
package main
func main(){}
執行命令go run hello.go
程序正確執行,但是由於我們沒有做任何其它操作,程序很快就退出了。
到目前為止,我們已經創建了自己的第一個程序。雖然沒啥功能,但是已經可以正常運行了。
讓我們繼續添加一行
內容:
package main
func main(){
Println("hello world")
}
運行,將會打印如下錯誤
./hello.go:4:2: undefined: Println
Println是向屏幕輸入內容。執行命令之后,編譯器報未定義。
為什么呢?
這里我們就需要用到包了。像Println這樣的函數存放在某些包中。然而,當前這些包由於我們沒有主動引入,但不能使用。如果我們需要使用這些包中的功能,首先需要import它們。
函數Println和其它讀寫文本和字符的函數,都存放在一個叫做fmt的包中——formatting的縮寫。
我們再添加幾行代碼:
package main
import "fmt"
func main(){
fmt.Println("hello world")
}
運行程序go run hello.go ,輸出如下:
hello world
我們只是在package下面添加了一個import語句,第一個Go程序已經正常運行了。import之后,Println可以通過 包名.的方式進行調用。
Go語言 “ _ ”(下划線)
“_”是特殊標識符,用來忽略結果。
1.下划線在import中
在Golang里,import的作用是導入其他package。
import 下划線(如:import _ hello/imp)的作用:當導入一個包時,該包下的文件里所有init()函數都會被執行,然而,有些時候我們並不需要把整個包都導入進來,僅僅是是希望它執行init()函數而已。這個時候就可以使用 import _ 引用該包。即使用【import _ 包路徑】只是引用該包,僅僅是為了調用init()函數,所以無法通過包名來調用包中的其他函數。
示例:
代碼結構
src
|
+--- main.go
|
+--- hello
|
+--- hello.go
main.go
package main
import _ "./hello"
func main() {
// hello.Print()
//編譯報錯:./main.go:6:5: undefined: hello
}
hello.go
package hello
import "fmt"
func init() {
fmt.Println("imp-init() come here.")
}
func Print() {
fmt.Println("Hello!")
}
輸出結果:
imp-init() come here.
2.下划線在代碼中
package main
import (
"os"
)
func main() {
buf := make([]byte, 1024)
f, _ := os.Open("/Users/***/Desktop/text.txt")
defer f.Close()
for {
n, _ := f.Read(buf)
if n == 0 {
break
}
os.Stdout.Write(buf[:n])
}
}
解釋1:
下划線意思是忽略這個變量.
比如os.Open,返回值為*os.File,error
普通寫法是f,err := os.Open("xxxxxxx")
如果此時不需要知道返回的錯誤值
就可以用f, _ := os.Open("xxxxxx")
如此則忽略了error變量
解釋2:
占位符,意思是那個位置本應賦給某個值,但是咱們不需要這個值。
所以就把該值賦給下划線,意思是丟掉不要。
這樣編譯器可以更好的優化,任何類型的單個值都可以丟給下划線。
這種情況是占位用的,方法返回兩個結果,而你只想要一個結果。
那另一個就用 "_" 占位,而如果用變量的話,不使用,編譯器是會報錯的。
補充:
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
第二個import就是不直接使用mysql包,只是執行一下這個包的init函數,把mysql的驅動注冊到sql包里,然后程序里就可以使用sql包來訪問mysql數據庫了。
運算符
全部運算符、分隔符,以及其他符號。
+ | & | += | &= | && | == | != | ( | ) |
---|---|---|---|---|---|---|---|---|
- | | | -= | |= | || | < | <= | [ | ] |
* | ^ | *= | ^= | <- | > | >= | { | } |
/ | << | /= | <<= | ++ | = | := | , | ; |
% | >> | %= | >>= | -- | ! | ... | . | : |
&^ | &^= |
運算符結合律全部從左到右。
優先級 | 運算符 | 說明 |
---|---|---|
high | * / & << >> & &^ | |
+ - | ^ | ||
== != < <= < >= | ||
<- | channel && | |
low | || |
簡單位運算演 。
0110 & 1011 = 0010 AND 都為 1。
0110 | 1011 = 1111 OR 少 個為 1。
0110 ^ 1011 = 1101 XOR 只能 個為 1。
0110 &^ 1011 = 0100 AND NOT 清除標志位。
標志位操作。
a := 0
a |= 1 << 2 // 0000100: 在 bit2 設置標志位。
a |= 1 << 6 // 1000100: 在 bit6 設置標志位
a = a &^ (1 << 6) // 0000100: 清除 bit6 標志位。
不支持運算符重載。尤其需要注意,"++"、"--" 是語句而非表達式。
n := 0
p := &n
// b := n++ // syntax error
// if n++ == 1 {} // syntax error
// ++n // syntax error
n++
*p++ // (*p)++
沒有 "~",取反運算也 "^"。
x := 1
x, ^x // 0001, -0010
Go命令
安裝了go環境的話,你可以在命令行執行go命令查看相關的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
bug start a bug report
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 env用於打印Go語言的環境信息。
go run命令可以編譯並運行命令源碼文件。
go get可以根據要求和實際情況從互聯網上下載或更新指定的代碼包及其依賴包,並對它們進行編譯和安裝。
go build命令用於編譯我們指定的源碼文件或代碼包以及它們的依賴包。
go install用於編譯並安裝指定的代碼包及它們的依賴包。
go clean命令會刪除掉執行其它命令時產生的一些文件和目錄。
go doc命令可以打印附於Go語言程序實體上的文檔。我們可以通過把程序實體的標識符作為該命令的參數來達到查看其文檔的目的。
go test命令用於對Go語言編寫的程序進行測試。
go list命令的作用是列出指定的代碼包的信息。
go fix會把指定代碼包的所有Go語言源碼文件中的舊版本代碼修正為新版本的代碼。
go vet是一個用於檢查Go語言源碼中靜態錯誤的簡單工具。
go tool pprof命令來交互式的訪問概要文件的內容。
用戶go get
無法下載翻牆的時候的包,可以用gopm
下載
什么是gopm
在nodejs中我們有npm,可以通過npm來下載安裝一些依賴包。在go中也開發了類似的東西,那就是gopm。這玩意兒是七牛開發的。在這里說下,七牛公司大部分程序都是用go語言編寫的,所以開發出這么一個方便的東西肯定也是合情合理的。
gopm 安裝
go get github.com/gpmgo/gopm
go install github.com/gpmgo/gopm
通過這個命令來安裝插件,默認的會存放到GOBIN,如果沒有配置%GOBIN%環境變量,那么會默認安裝到%GOPATH%下的bin目錄,為了我們操作方便,我們把GOBIN加到%PATH%下。
使用說明
NAME:
Gopm - Go Package Manager
USAGE:
Gopm [global options] command [command options] [arguments...]
VERSION:
0.8.8.0307 Beta
COMMANDS:
list list all dependencies of current project
gen generate a gopmfile for current Go project
get fetch remote package(s) and dependencies
bin download and link dependencies and build binary
config configure gopm settings
run link dependencies and go run
test link dependencies and go test
build link dependencies and go build
install link dependencies and go install
clean clean all temporary files
update check and update gopm resources including itself
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--noterm, -n disable color output
--strict, -s strict mode
--debug, -d debug mode
--help, -h show help
--version, -v print the version
exmaple
gopm get -g -v -u golang.org/x/tools/cmd/goimports
通過gopm get xxx
,可以將指定的包下載到gopm的本地倉庫~/.gopm/repos
(建議使用) 通過'gopm get -g xxx',可以將指定的包下載到GOPATH下。(建議使用) 通過'gopm get -l xxx',可以將指定的包下載到當前所在目錄(不常用)