1 回答

TA貢獻1790條經驗 獲得超9個贊
您需要一個指向指針的指針來更改指針的值。
這是您的代碼示例,已修改為執行此操作 (?playground?):
package main
import (
? ? "fmt"
)
type position struct {
? ? x int
? ? y int
}
func destroy(p **position) {
? ? *p = nil
}
func main() {
? ? p1 := &position{1, 1}
? ? destroy(&p1)
? ? if p1 == nil {
? ? ? ? fmt.Println("p1 == nil")
? ? } else {
? ? ? ? fmt.Println(p1)
? ? }
}
在您當前的代碼中
func destroy(p *position) {
? ? p = nil
}
在里面destroy,p是一個保存結構地址的值position。通過給p自己分配一些東西,你只是讓它保存一些其他position結構(或nil)的地址。您沒有修改傳入的原始指針。
這與嘗試通過分配給它來修改其參數的函數沒有什么不同:
// This will not actually modify the argument passed in by the caller
func setto2(value int) {
? value = 2
}
go 規范在關于調用和調用參數的部分中說:
在對它們求值后,調用的參數按值傳遞給函數,被調用的函數開始執行。函數的返回參數在函數返回時按值傳遞回調用函數。
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報