* ch10.1 part

This commit is contained in:
leisore
2015-06-08 23:41:46 +08:00
parent 5acf26cee6
commit 5df7829fb6
3 changed files with 23 additions and 3 deletions

View File

@@ -134,7 +134,7 @@ type Point struct { x, y int }
作为结构体字面量初始化:
![](images/10.1_fig10.1.jpg?raw=true)
![](images/10.1_fig10.1-2.jpg?raw=true)
类型strcut1在定义它的包pack1中必须是唯一的它的完全类型名是`pack1.struct1`
@@ -174,9 +174,9 @@ func main() {
fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
// 3—struct as a literal:
pers3 := &Person{Chris,Woodward}
pers3 := &Person{"Chris","Woodward"}
upPerson(pers3)
fmt.Printf(The name of the person is %s %s\n, pers3.firstName, pers3.lastName)
fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName)
}
```
@@ -188,6 +188,26 @@ func main() {
The name of the person is CHRIS WOODWARD
The name of the person is CHRIS WOODWARD
在上面例子的第二种情况中,像`pers2.lastName="Woodward"`这样,可以直接通过指针,像`pers2.lastName="Woodward"`这样给结构体成员赋值没有像C++那样需要使用`->`操作符Go会自动做这样的转换。
注意也可以通过解指针的方式来设置值:
```go
(*pers2).lastName = "Woodward"
```
**结构体和内存布局**
Go语言中的结构体和它所包含的数据在内存中是以连续块的形式存在的即使结构体中嵌套有其他的结构体这带来了很大的性能优势。不像Java中的引用类型一个对象和它里面包含的对象可能会在不同的内存空间中Go中的指针和这个很像。下面的例子清晰的说明了这些情况
```go
type Rect1 struct {Min, Max Point }
type Rect2 struct {Min, Max *Point }
```
![](images/10.1_fig10.2.jpg?raw=true)
**递归结构体**
**练习9.2**

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB