亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從方法或函數中將指針設置為 nil

從方法或函數中將指針設置為 nil

Go
紅糖糍粑 2023-06-05 19:40:13
為什么這兩個destroy函數都不會將指針更改為 nil,我該如何創建這樣的函數?package mainimport (    "fmt")type position struct {    x int    y int}func (p *position) destroy() {    p = nil}func destroy(p *position) {    p = nil}func main() {    p1 := &position{1,1}    p2 := &position{2,2}    p1.destroy()    destroy(p2)    if p1 == nil {        fmt.Println("p1 == nil")    } else {        fmt.Println(p1)    }    if p2 == nil {        fmt.Println("p2 == nil")    } else {        fmt.Println(p2)    }}輸出:&{1 1}&{2 2}https://play.golang.org/p/BmZjX1Hw24u
查看完整描述

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 規范在關于調用和調用參數的部分中說:

在對它們求值后,調用的參數按值傳遞給函數,被調用的函數開始執行。函數的返回參數在函數返回時按值傳遞回調用函數。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號