Skip to content

Commit

Permalink
Merge pull request hantmac#125 from themoonbear/6.2.4
Browse files Browse the repository at this point in the history
添加6.2.4
  • Loading branch information
hantmac committed May 21, 2019
2 parents 6bd1738 + 91dfc84 commit b03d914
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
- [chapter 6.2.1 匿名函数](https://github.com/hantmac/Mastering_Go_ZH_CN/tree/master/eBook/chapter6/06.2.1.md)
- [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 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
48 changes: 48 additions & 0 deletions eBook/chapter6/06.2.4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# 参数为指针的函数

函数可以有指针类型的参数。`ptrFun.go` 的代码将说明指针作为函数参数的使用。

`ptfFun.go` 的第一部分如下:

```go
package main

import (
"fmt"
)

func getPtr(v *float64) float64 {
return *v * *v
}
```

`getPrt()` 函数接收一个指向 `float64` 值的指针。

第二段代码如下:

```go
func main() {
x := 12.2
fmt.Println(getPrt(&x))
x = 12
fmt.Println(getPtr(&x))
}
```

这里您需要传递变量的地址给 `getPtr()` 函数,因为它需要一个指针参数,传地址需要在变量前放一个 & 符号(&x)。

执行 `ptrFun.go` 产生如下输出:

```shell
$go run ptrFun.go
148.83999999999997
144
```

如果您直接传值如:`12.2``getPtr()`,并调用它如:`getPtr(12.12)`,那么程序编译失败,显示下面的错误信息:

```shell
$go run ptrFun.go
# command-line-arguments
./ptrFun.go:15:21: cannot use 12.12 (type float64) as type *float64 in argument to getPtr
```
16 changes: 16 additions & 0 deletions eBook/examples/chapter6/ptrFun.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

import (
"fmt"
)

func getPtr(v *float64) float64 {
return *v * *v
}

func main() {
x := 12.2
fmt.Println(getPrt(&x))
x = 12
fmt.Println(getPtr(&x))
}

0 comments on commit b03d914

Please sign in to comment.