Skip to content

Commit

Permalink
04.4.1.md
Browse files Browse the repository at this point in the history
  • Loading branch information
unknwon committed Apr 21, 2013
1 parent 258c50e commit d658c08
Show file tree
Hide file tree
Showing 24 changed files with 447 additions and 18 deletions.
110 changes: 109 additions & 1 deletion eBook/04.4.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
##啊哦,亲,你看得也太快了。。。还没翻译完呢 0 0
要不等到 ***2013 年 4 月 22*** 再来看看吧~~
要不等到 ***2013 年 4 月 23*** 再来看看吧~~

这里还有一些其它的学习资源噢~

Expand All @@ -13,7 +13,115 @@
- [Golang中国](http://golang.tc)

#4.4 变量
#4.4.1 简介
声明变量的一般形式是使用 `var` 关键字:`var identifier type`

需要注意的是,Go 和许多编程语言不同,它在声明变量时将变量的类型放在变量的名称之后。Go 为什么要选择这么做呢?

首先,它是为了避免像 C 语言中那样含糊不清的声明形式,例如:`int* a, b;`。在这个例子中,只有 a 是指针而 b 不是。如果你想要这两个变量都是指针,则需要将它们分开书写(你可以在该页面找到有关于这个话题的更多讨论:[http://blog.golang.org/2010/07/gos-declaration-syntax.html](http://blog.golang.org/2010/07/gos-declaration-syntax.html))。

而在 Go 中,则可以和轻松地将它们都声明为指针类型:`var a, b *int`

其次,这种语法能够按照从左至右的顺序阅读,使得代码更加容易理解。

示例:

var a int
var b bool
var str string

你也可以改写成这种形式:

var (
a int
b bool
str string
)

这种因式分解关键字的写法一般用于声明全局变量。

当一个变量被声明之后,系统自动赋予它该类型的零值:int 为 0,flost 为 0.0,bool 为 false,string 为空字符串,指针为 nil。记住,所有的内存在 Go 中都是经过初始化的。

变量的命名规则遵循骆驼命名法,即首个单词小写,每个新单词的首字母大写,例如:`numShips`, `startDate`

但如果你的全局变量希望能够被外部包所使用,则需要将首个单词的首字母也大写(第 4.2 节:可见性规则)。

一个变量(常量、类型或函数)在程序中都有一定的作用范围,称之为作用域。如果一个变量在函数体外声明,则被认为是全局变量,可以在整个包甚至外部包(被导出后)使用,不管你声明在哪个源文件里或在哪个源文件里调用该变量。

在函数体内声明的变量称之为局部变量,它们的作用域只在函数体内,参数和返回值变量也是局部变量。在第 5 章,我们将会学习到像 if 和 for 这些控制结构,而在这些结构中声明的变量的作用域只在相应的代码块内。一般情况下,局部变量的作用域可以通过代码块(用大括号括起来的部分)判断。

尽管变量的标识符必须是唯一的,但你可以在某个代码块的内层代码块中使用相同名称的变量,则此时外部的同名变量将会暂时隐藏(结束内部代码块的执行后隐藏的外部同名变量又会出现,而内部同名变量则被释放),你任何的操作都只会影响内部代码块的局部变量。

变量可以编译期间就被赋值,赋值给变量使用运算符等号 `=`,当然你也可以在运行时对变量进行赋值操作。

示例:

a = 15
b = false

一般情况下,只有类型相同的变量之间才可以相互赋值,例如:`a = b`

声明与赋值(初始化)语句也可以组合起来。

示例:

var identifier [type] = value
var a int = 15
var i = 5
var b bool = false
var str string = “Go says hello to the world!”

但是 Go 编译器的智商已经高到可以根据变量的值来自动推断其类型,这有点像 Ruby 和 Python 这类动态语言,只不过它们是在运行时进行推断,而 Go 是在编译时就已经完成推断过程。因此,你还可以使用下面的这些形式来声明及初始化变量:

var a = 15
var b = false
var str = “Go says hello to the world!”

或:

var (
a = 15
b = false
str = “Go says hello to the world!”
numShips = 50
city string
)

不过自动推断类型并不是任何时候都适用的,当你想要给变量的类型并不是自动推断出的某种类型时,你还是需要显式指定变量的类型,例如:`var n int64 = 2`

然而,`var a` 这种语法是不正确的,因为编译器没有任何可以用于自动推断类型的依据。变量的类型也可以在运行时实现自动推断,例如:

var (
HOME = os.Getenv(“HOME”)
USER = os.Getenv(“USER”)
GOROOT = os.Getenv(“GOROOT”)
)

这种写法主要用于声明包级别的全局变量,当你在函数体内声明局部变量时,应使用简短声明语法 `:=`,例如:`a := 1`

下面这个例子展示了如何在运行时获取所在的操作系统类型,它通过 `os` 包中的函数 `os.Getenv()` 来获取环境变量中的值,并保存到 string 类型的局部变量 `path` 中。

Example 4.5 [goos.go](examples/chapter_4/goos.go)

package main

import (
“fmt”
“os”
)

func main() {
var goos string = os.Getenv(“GOOS”)
fmt.Printf(“The operating system is: %s\n”, goos)
path := os.Getenv(“PATH”)
fmt.Printf(“Path is %s\n”, path)
}

如果你在 Windows 下运行这段代码,则会输出 `The operating system is: windows` 以及相应的环境变量的值;如果你在 Linux 下运行这段代码,则会输出 `The operating system is: linux` 以及相应的的环境变量的值。

这里用到了 `Printf` 的格式化输出的功能(第 4.4.3 节)。

#4.4.2 值类型和引用类型

##链接
- [目录](directory.md)
Expand Down
7 changes: 4 additions & 3 deletions eBook/examples/chapter_4/alias.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main
import fm "fmt" // alias3

func main() {
fm.Println("hello, world")
import fm "fmt" // alias

func main() {
fm.Println("hello, world")
}
18 changes: 18 additions & 0 deletions eBook/examples/chapter_4/casting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main
import "fmt"

func main() {
var n int16 = 34
var m int32

// compiler error: cannot use n (type int16) as type int32 in assignment
//m = n
m = int32(n)

fmt.Printf("32 bit int is: %d\n", m)
fmt.Printf("16 bit int is: %d\n", n)
}
/* Output:
32 bit int is: 34
16 bit int is: 34
*/
22 changes: 22 additions & 0 deletions eBook/examples/chapter_4/char.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// char.go
package main

import (
"fmt"
)

func main() {
var ch int = '\u0041'
var ch2 int = '\u03B2'
var ch3 int = '\U00101234'
fmt.Printf("%d - %d - %d\n", ch, ch2, ch3)
fmt.Printf("%c - %c - %c\n", ch, ch2, ch3)
fmt.Printf("%X - %X - %X\n", ch, ch2, ch3)
fmt.Printf("%U - %U - %U", ch, ch2, ch3)
}
/* Ouput:
65 - 946 - 1053236
A - β - 􁈴
41 - 3B2 - 101234
U+0041 - U+03B2 - U+101234
*/
17 changes: 17 additions & 0 deletions eBook/examples/chapter_4/count_substring.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package main

import (
"fmt"
"strings"
)

func main() {
var str string = "Hello, how is it going, Hugo?"
var manyG = "gggggggggg"

fmt.Printf("Number of H's in %s is: ", str)
fmt.Printf("%d\n", strings.Count(str, "H"))

fmt.Printf("Number of double g's in %s is: ", manyG)
fmt.Printf("%d\n", strings.Count(manyG, "gg"))
}
13 changes: 13 additions & 0 deletions eBook/examples/chapter_4/goos.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import (
"fmt"
"os"
)

func main() {
var goos string = os.Getenv("GOOS")
fmt.Printf("The operating system is: %s\n", goos)
path := os.Getenv("PATH")
fmt.Printf("Path is %s\n", path)
}
17 changes: 9 additions & 8 deletions eBook/examples/chapter_4/gotemplate.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"fmt"
"fmt"
)

const c = "C"
Expand All @@ -10,20 +10,21 @@ var v int = 5

type T struct{}

func init() { // initialization of package
func init() {
// initialization of package
}

func main() {
var a int
Func1()
// ...
fmt.Println(a)
var a int
Func1()
// ...
fmt.Println(a)
}

func (t T) Method1() {
//...
//...
}

func Func1() { // exported function Func1
//...
//...
}
6 changes: 2 additions & 4 deletions eBook/examples/chapter_4/hello_world.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
// hello_world.go
package main

import "fmt"
import "fmt"

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

3 changes: 1 addition & 2 deletions eBook/examples/chapter_4/hello_world2.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ package main
import "fmt" // Package implementing formatted I/O.

func main() {
fmt.Printf("Καλημέρα κόσμε; or こんにちは 世界\n")
fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n")
}

21 changes: 21 additions & 0 deletions eBook/examples/chapter_4/index_in_string.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"fmt"
"strings"
)

func main() {
var str string = "Hi, I'm Marc, Hi."

fmt.Printf("The position of \"Marc\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Marc"))

fmt.Printf("The position of the first instance of \"Hi\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Hi"))
fmt.Printf("The position of the last instance of \"Hi\" is: ")
fmt.Printf("%d\n", strings.LastIndex(str, "Hi"))

fmt.Printf("The position of \"Burger\" is: ")
fmt.Printf("%d\n", strings.Index(str, "Burger"))
}
9 changes: 9 additions & 0 deletions eBook/examples/chapter_4/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package trans

import "math"

var Pi float64

func init() {
Pi = 4 * math.Atan(1) // init() function computes Pi
}
12 changes: 12 additions & 0 deletions eBook/examples/chapter_4/pointer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

import "fmt"

func main() {
var i1 = 5
fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1)

var intP *int
intP = &i1
fmt.Printf("The value at memory location %p is %d\n", intP, *intP)
}
14 changes: 14 additions & 0 deletions eBook/examples/chapter_4/presuffix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

import (
"fmt"
"strings"
)

func main() {
var str string = "This is an example of a string"

fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
}
// Output: T/F? Does the string "This is an example of a string" have prefix Th? true
28 changes: 28 additions & 0 deletions eBook/examples/chapter_4/random.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
for i := 0; i < 10; i++ {
a := rand.Int()
fmt.Printf("%d / ", a)
}
for i := 0; i < 5; i++ {
r := rand.Intn(8)
fmt.Printf("%d / ", r)
}
fmt.Println()
timens := int64(time.Now().Nanosecond())
rand.Seed(timens)
for i := 0; i < 10; i++ {
fmt.Printf("%2.2f / ", 100*rand.Float32())
}
}
/* Output:
134020434 / 1597969999 / 1721070109 / 2068675587 / 1237770961 / 220031192 / 2031484958 / 583324308 / 958990240 / 413002649 / 6 / 7 / 2 / 1 / 0 /
22.84 / 10.12 / 44.32 / 58.58 / 15.49 / 12.23 / 30.16 / 88.48 / 34.26 / 27.18 /
*/
14 changes: 14 additions & 0 deletions eBook/examples/chapter_4/repeat_string.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

import (
"fmt"
"strings"
)

func main() {
var origS string = "Hi there! "
var newS string

newS = strings.Repeat(origS, 3)
fmt.Printf("The new repeated string is: %s\n", newS)
}
20 changes: 20 additions & 0 deletions eBook/examples/chapter_4/string_conversion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"fmt"
"strconv"
)

func main() {
var orig string = "666"
var an int
var newS string

fmt.Printf("The size of ints is: %d\n", strconv.IntSize)

an, _ = strconv.Atoi(orig)
fmt.Printf("The integer is: %d\n", an)
an = an + 5
newS = strconv.Itoa(an)
fmt.Printf("The new string is: %s\n", newS)
}
Loading

0 comments on commit d658c08

Please sign in to comment.