首次提交:初始化项目代码
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 函数传指针,修改外部变量
|
||||
func increment(x *int) {
|
||||
*x++
|
||||
}
|
||||
|
||||
// 指针作为返回值
|
||||
func createInt() *int {
|
||||
var num int = 100
|
||||
return &num
|
||||
}
|
||||
|
||||
func main() {
|
||||
var x int = 20
|
||||
var p *int = &x // p是指向x的指针
|
||||
|
||||
fmt.Printf("x的值: %d, x的地址: %p\n", x, &x)
|
||||
fmt.Printf("p的值(地址): %p, p指向的值: %d\n", p, *p)
|
||||
|
||||
// 通过指针修改值
|
||||
*p = 21
|
||||
fmt.Printf("修改后x的值: %d\n", x) // 输出21
|
||||
|
||||
// 函数传指针
|
||||
increment(&x)
|
||||
fmt.Printf("increment后x值: %d\n", x) // 输出22
|
||||
|
||||
// 指针作为返回值
|
||||
p2 := createInt()
|
||||
fmt.Printf("createInt返回值: %d, 地址: %p\n", *p2, p2) // 输出100及地址
|
||||
|
||||
// 指针与nil比较
|
||||
var p3 *int
|
||||
if p3 == nil {
|
||||
fmt.Println("p3是nil指针")
|
||||
}
|
||||
|
||||
// 错误示例(编译不通过)
|
||||
// p++ // 报错:invalid operation: p++ (non-numeric type *int)
|
||||
}
|
||||
Reference in New Issue
Block a user