forked from hantmac/Mastering_Go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b03d914
commit 66525f5
Showing
3 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |