04.4.1.md

This commit is contained in:
Unknown
2013-04-21 19:25:28 -04:00
parent 258c50e72a
commit d658c086ca
24 changed files with 447 additions and 18 deletions

View File

@@ -1,5 +1,5 @@
##啊哦,亲,你看得也太快了。。。还没翻译完呢 0 0
要不等到 ***2013 年 4 月 22 日*** 再来看看吧~~
要不等到 ***2013 年 4 月 23 日*** 再来看看吧~~
这里还有一些其它的学习资源噢~
@@ -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 为 0flost 为 0.0bool 为 falsestring 为空字符串,指针为 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)

View File

@@ -1,5 +1,6 @@
package main
import fm "fmt" // alias3
import fm "fmt" // alias
func main() {
fm.Println("hello, world")

View File

@@ -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
*/

View File

@@ -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
*/

View File

@@ -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"))
}

View File

@@ -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)
}

View File

@@ -10,7 +10,8 @@ var v int = 5
type T struct{}
func init() { // initialization of package
func init() {
// initialization of package
}
func main() {

View File

@@ -1,4 +1,3 @@
// hello_world.go
package main
import "fmt"
@@ -6,4 +5,3 @@ import "fmt"
func main() {
fmt.Println("hello, world")
}

View File

@@ -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")
}

View File

@@ -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"))
}

View File

@@ -0,0 +1,9 @@
package trans
import "math"
var Pi float64
func init() {
Pi = 4 * math.Atan(1) // init() function computes Pi
}

View File

@@ -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)
}

View File

@@ -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

View File

@@ -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 /
*/

View File

@@ -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)
}

View File

@@ -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)
}

View File

@@ -0,0 +1,13 @@
package main
import "fmt"
func main() {
s := "good bye"
var p *string = &s
*p = "ciao"
fmt.Printf("Here is the pointer p: %p\n", p) // prints address
fmt.Printf("Here is the string *p: %s\n", *p) // prints string
fmt.Printf("Here is the string s: %s\n", s) // prints same string
}

View File

@@ -0,0 +1,33 @@
// strings.go
package main
import (
"fmt"
"strings"
)
func main() {
str := "The quick brown fox jumps over the lazy dog"
sl := strings.Fields(str)
fmt.Printf("Splitted in slice: %v\n", sl)
for _, val := range sl {
fmt.Printf("%s - ", val)
}
fmt.Println()
str2 := "GO1|The ABC of Go|25"
sl2 := strings.Split(str2, "|")
fmt.Printf("Splitted in slice: %v\n", sl2)
for _, val := range sl2 {
fmt.Printf("%s - ", val)
}
fmt.Println()
str3 := strings.Join(sl2,";")
fmt.Printf("sl2 joined by ;: %s\n", str3)
}
/* Output:
Splitted in slice: [The quick brown fox jumps over the lazy dog]
The - quick - brown - fox - jumps - over - the - lazy - dog -
Splitted in slice: [GO1 The ABC of Go 25]
GO1 - The ABC of Go - 25 -
sl2 joined by ;: GO1;The ABC of Go;25
*/

View File

@@ -0,0 +1,11 @@
// testcrash.go
// compiles , but crashes
package main
func main() {
var p *int = nil
*p = 0
}
// in Windows: stops only with: <exit code="-1073741819" msg="process crashed"/>
// runtime error: invalid memory address or nil pointer dereference

View File

@@ -0,0 +1,27 @@
package main
import (
"fmt"
"time"
)
var week time.Duration
func main() {
t := time.Now()
fmt.Println(t) // Wed Dec 21 09:52:14 +0100 RST 2011
fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year()) // 21.12.2011
t = time.Now().UTC()
fmt.Println(t) // Wed Dec 21 08:52:14 +0000 UTC 2011
fmt.Println(time.Now()) // Wed Dec 21 09:52:14 +0100 RST 2011
// calculating times:
week = 60 * 60 * 24 * 7 * 1e9 // must be in nanosec
week_from_now := t.Add(week)
fmt.Println(week_from_now) // Wed Dec 28 08:52:14 +0000 UTC 2011
// formatting times:
fmt.Println(t.Format(time.RFC822)) // 21 Dec 11 0852 UTC
fmt.Println(t.Format(time.ANSIC)) // Wed Dec 21 08:56:34 2011
fmt.Println(t.Format("02 Jan 2006 15:04")) // 21 Dec 2011 08:52
s := t.Format("20060102")
fmt.Println(t, "=>", s) // Wed Dec 21 08:52:14 +0000 UTC 2011 => 20111221
}

View File

@@ -0,0 +1,18 @@
package main
import (
"fmt"
"strings"
)
func main() {
var orig string = "Hey, how are you George?"
var lower string
var upper string
fmt.Printf("The original string is: %s\n", orig)
lower = strings.ToLower(orig)
fmt.Printf("The lowercase string is: %s\n", lower)
upper = strings.ToUpper(orig)
fmt.Printf("The uppercase string is: %s\n", upper)
}

View File

@@ -0,0 +1,11 @@
package main
import "fmt"
type TZ int
func main() {
var a, b TZ = 3, 4
c := a + b
fmt.Printf("c has the value: %d", c)
}

View File

@@ -0,0 +1,9 @@
package main
func main() {
var a int
var b int32
a = 15
b = a + a // compiler error
b = b + 5 // ok: 5 is a constant
}

View File

@@ -0,0 +1,12 @@
package main
import (
"fmt"
"./trans"
)
var twoPi = 2 * trans.Pi // decl computes twoPi
func main() {
fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586
}