Merge pull request #34 from charleyzhang/patch-1

Update 04.4.md
This commit is contained in:
Joe Chen
2013-12-16 19:04:26 -08:00

View File

@@ -55,7 +55,7 @@
var a int = 15 var a int = 15
var i = 5 var i = 5
var b bool = false var b bool = false
var str string = Go says hello to the world! var str string = "Go says hello to the world!"
但是 Go 编译器的智商已经高到可以根据变量的值来自动推断其类型,这有点像 Ruby 和 Python 这类动态语言,只不过它们是在运行时进行推断,而 Go 是在编译时就已经完成推断过程。因此,你还可以使用下面的这些形式来声明及初始化变量: 但是 Go 编译器的智商已经高到可以根据变量的值来自动推断其类型,这有点像 Ruby 和 Python 这类动态语言,只不过它们是在运行时进行推断,而 Go 是在编译时就已经完成推断过程。因此,你还可以使用下面的这些形式来声明及初始化变量:
@@ -68,7 +68,7 @@
var ( var (
a = 15 a = 15
b = false b = false
str = Go says hello to the world! str = "Go says hello to the world!"
numShips = 50 numShips = 50
city string city string
) )
@@ -78,9 +78,9 @@
然而,`var a` 这种语法是不正确的,因为编译器没有任何可以用于自动推断类型的依据。变量的类型也可以在运行时实现自动推断,例如: 然而,`var a` 这种语法是不正确的,因为编译器没有任何可以用于自动推断类型的依据。变量的类型也可以在运行时实现自动推断,例如:
var ( var (
HOME = os.Getenv(HOME) HOME = os.Getenv("HOME")
USER = os.Getenv(USER) USER = os.Getenv("USER")
GOROOT = os.Getenv(GOROOT) GOROOT = os.Getenv("GOROOT")
) )
这种写法主要用于声明包级别的全局变量,当你在函数体内声明局部变量时,应使用简短声明语法 `:=`,例如:`a := 1` 这种写法主要用于声明包级别的全局变量,当你在函数体内声明局部变量时,应使用简短声明语法 `:=`,例如:`a := 1`
@@ -92,15 +92,15 @@ Example 4.5 [goos.go](examples/chapter_4/goos.go)
package main package main
import ( import (
fmt "fmt"
os "os"
) )
func main() { func main() {
var goos string = os.Getenv(GOOS) var goos string = os.Getenv("GOOS")
fmt.Printf(The operating system is: %s\n, goos) fmt.Printf("The operating system is: %s\n", goos)
path := os.Getenv(PATH) path := os.Getenv("PATH")
fmt.Printf(Path is %s\n, path) fmt.Printf("Path is %s\n", path)
} }
如果你在 Windows 下运行这段代码,则会输出 `The operating system is: windows` 以及相应的环境变量的值;如果你在 Linux 下运行这段代码,则会输出 `The operating system is: linux` 以及相应的的环境变量的值。 如果你在 Windows 下运行这段代码,则会输出 `The operating system is: windows` 以及相应的环境变量的值;如果你在 Linux 下运行这段代码,则会输出 `The operating system is: linux` 以及相应的的环境变量的值。
@@ -170,7 +170,7 @@ a 和 b 的类型int 和 bool将由编译器自动推断。
func main() { func main() {
var a string = "abc" var a string = "abc"
fmt.Println(hello, world) fmt.Println("hello, world")
} }
尝试编译这段代码将得到错误 `a declared and not used` 尝试编译这段代码将得到错误 `a declared and not used`