* 添加部分10.1内容

This commit is contained in:
leisore
2015-06-05 18:59:16 +08:00
parent 9c01119c3e
commit 5acf26cee6

View File

@@ -136,6 +136,58 @@ type Point struct { x, y int }
![](images/10.1_fig10.1.jpg?raw=true)
类型strcut1在定义它的包pack1中必须是唯一的它的完全类型名是`pack1.struct1`
下面的例子[Listing 10.2—person.go](examples/person.go)显示了一个结构体Person一个方法方法有一个类型为*Person的参数因此对象本身是可以被改变的以及三种不同的调用这个方法的方式
```go
package main
import (
"fmt"
"strings"
)
type Person struct {
firstName string
lastName string
}
func upPerson(p *Person) {
p.firstName = strings.ToUpper(p.firstName)
p.lastName = strings.ToUpper(p.lastName)
}
func main() {
// 1-struct as a value type:
var pers1 Person
pers1.firstName = "Chris"
pers1.lastName = "Woodward"
upPerson(&pers1)
fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
// 2—struct as a pointer:
pers2 := new(Person)
pers2.firstName = "Chris"
pers2.lastName = "Woodward"
(*pers2).lastName = "Woodward" // 这是合法的
upPerson(pers2)
fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
// 3—struct as a literal:
pers3 := &Person{Chris,Woodward}
upPerson(pers3)
fmt.Printf(The name of the person is %s %s\n, pers3.firstName, pers3.lastName)
}
```
第2种情况
输出:
The name of the person is CHRIS WOODWARD
The name of the person is CHRIS WOODWARD
The name of the person is CHRIS WOODWARD
**练习9.2**