mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 03:06:41 +08:00
* ch10.1 part
This commit is contained in:
@@ -134,7 +134,7 @@ type Point struct { x, y int }
|
||||
|
||||
作为结构体字面量初始化:
|
||||
|
||||

|
||||

|
||||
|
||||
类型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 }
|
||||
```
|
||||
|
||||

|
||||
|
||||
**递归结构体**
|
||||
|
||||
**练习9.2**
|
||||
|
||||
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
BIN
eBook/images/10.1_fig10.2.jpg
Normal file
BIN
eBook/images/10.1_fig10.2.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
Reference in New Issue
Block a user