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.
Merge pull request hantmac#125 from themoonbear/6.2.4
添加6.2.4
- Loading branch information
Showing
3 changed files
with
65 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,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 | ||
``` |
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 getPtr(v *float64) float64 { | ||
return *v * *v | ||
} | ||
|
||
func main() { | ||
x := 12.2 | ||
fmt.Println(getPrt(&x)) | ||
x = 12 | ||
fmt.Println(getPtr(&x)) | ||
} |