Skip to content

Commit

Permalink
添加6.2.5
Browse files Browse the repository at this point in the history
  • Loading branch information
themoonbear committed Jun 4, 2019
1 parent b03d914 commit 66525f5
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
- [chapter 6.2.2 多返回值的函数](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter6/06.2.2.md)
- [chapter 6.2.3 可命名的函数返回值](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter6/06.2.3.md)
- [chapter 6.2.4 参数为指针的函数](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter6/06.2.4.md)
- [chapter 6.2.5 返回值为指针的函数](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter6/06.2.5.md)
- [chapter 7 反射和接口](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter7)
- [07.1 类型方法](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter7/07.1.md)
- [07.2 Go的接口](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter7/07.2.md)
Expand Down
47 changes: 47 additions & 0 deletions eBook/chapter6/06.2.5.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 返回值为指针的函数

如您在[第四章](https://github.com/hantmac/Mastering_Go_ZH_CN/blob/master/eBook/chapter4/04.0.md)了解到的,在 `pointerStruct.go` 程序中介绍的*复合类型的使用*,它是一个非常好的练习,使用一个独立的函数来创建一个新的结构变量并返回指向它的指针。因此,函数返回指针是非常常见的。通常讲,函数简化程序结构并让开发者把较重要的处理逻辑集中起来,而不是总是复制相同的代码。这节将使用一个非常简单的例子,`returnPtr.go`

`returnPtr.go` 的第一部分代码如下:

```go
package main

import (
"fmt"
)

func returnPtr(x int) *int {
y := x * x
return &y
}
```

除了必须的引入部分,这段代码定义了一个返回 `int` 变量指针的新函数。唯一要记住的是使用 `&y``return` 表达式来返回 `y` 变量的内存地址。

`returnPtr.go` 的第二部分如下:

```go
func main() {
sq := returnPtr(10)
fmt.Println("sq:", *sq)
```
如您所知,`*` 符号**解引用一个指针变量**,就是它返回存储在内存地址里的实际值而不是内地地址本身。
`returnPtr.go` 的最后一段代码如下:
```go
fmt.Println("sq:", sq)
}
```

这段代码返回 `sq` 变量的内存地址,而不是存储在它里面的 `int` 值。

执行 `returnPtr.go` 将看到如下输出(内存地址可能会不同):

```shell
$go run returnPtr.go
sq: 100
sq: 0xc420014088
```
16 changes: 16 additions & 0 deletions eBook/examples/chapter6/returnPtr.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

import (
"fmt"
)

func returnPtr(x int) *int {
y := x * x
return &y
}

func main() {
sq := returnPtr(10)
fmt.Println("sq:", *sq)
fmt.Println("sq:", sq)
}

0 comments on commit 66525f5

Please sign in to comment.