首頁  >  文章  >  後端開發  >  Go中如何透過指標接收器方法修改值?

Go中如何透過指標接收器方法修改值?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-14 21:52:02940瀏覽

How to Modify Values Through Pointer Receiver Methods in Go?

Pointer Receiver Methods and Value Modification in Go

In Go, a pointer receiver function allows you to modify the value of the receiver object. However, understanding how pointers work in Go is crucial for successful implementation.

Issue Resolution

When trying to modify the value of a simple type through a pointer receiver method, one might encounter situations where the changes do not persist outside the method. This is because all method arguments, including the receiver, are copied locally within the method's execution.

Method Argument Copy

In the example provided:

func (fi *FooInt) FromString(i string) {
    num, _ := strconv.Atoi(i)
    tmp := FooInt(num)
    fi = &tmp
}

The fi pointer argument is a copy of the original fi pointer in main. Therefore, changes made to the copied fi pointer within the FromString method only affect the local copy, not the original pointer.

Solution

To resolve this, there are a few options:

  1. Return the Updated Pointer:

Create a return statement that assigns the updated pointer to the receiver, and then reassign the returned pointer in main.

// Return the updated pointer and reassign it in main
func (fi *FooInt) FromString(i string) *FooInt {
    num, _ := strconv.Atoi(i)
    tmp := FooInt(num)
    return &tmp
}

// Reassign the updated pointer in main
func main() {
    var fi *FooInt
    fi = fi.FromString("5")
    fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5
}
  1. Pass a Non-nil Pointer:

Pass a non-nil pointer of the target type as an argument to the method.

// Pass a non-nil pointer as an argument
func (fi *FooInt) FromString(i string, p **FooInt) {
    num, _ := strconv.Atoi(i)
    tmp := FooInt(num)
    *p = &tmp
}

// Create a non-nil pointer and pass it to the method in main
func main() {
    var fi *FooInt
    fi.FromString("5", &fi)
    fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5
}
  1. Ensure Non-Nil Receiver:

Check if the receiver pointer is non-nil before modifying it.

// Check if the receiver is non-nil before modifying
func (fi *FooInt) FromString(i string) {
    if fi == nil {
        return
    }
    num, _ := strconv.Atoi(i)
    *fi = FooInt(num)
}

// Create a non-nil receiver in main
func main() {
    fi := new(FooInt)
    fi.FromString("5")
    fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5
}

以上是Go中如何透過指標接收器方法修改值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn