首頁 > 後端開發 > Golang > 為什麼我的 Go struct 欄位修改後會恢復為原始值?

為什麼我的 Go struct 欄位修改後會恢復為原始值?

Linda Hamilton
發布: 2024-11-15 15:45:02
原創
856 人瀏覽過

Why Does My Go Struct Field Revert to Its Original Value When Modified?

Struct Field Reversion in Go

When attempting to modify a field in a struct within a Go program, you may encounter a scenario where the field seems to revert to its original value. This issue arises due to the way structures are passed by value in Go.

In your code, the MockConnector struct has two fields: last_command and value. The sendCommand method of MockConnector modifies these fields. However, when you call manager.sendMessage from the TVManager struct, you pass the connector instance as a value. This means that sendCommand receives a copy of the connector struct, rather than a reference to the original.

To resolve this issue, you need to use pointers to the structures involved. By passing a pointer to a structure, you pass a reference to the actual structure in memory. This allows you to modify the fields of the structure directly.

Corrected Code:

func (this *MockConnector) sendCommand(payload map[string]string) {
    fmt.Println("0", this)
    this.last_command = payload
    this.value = true
    fmt.Println("0", this)
}
登入後複製

By modifying the sendCommand method to receive a pointer to the MockConnector struct, you now modify the actual connector instance instead of just a copy.

Receiver Name:

Additionally, it's considered best practice to avoid using this as the receiver name in Go struct methods. Instead, use a more descriptive name to indicate the type of receiver.

Consistent Method Set:

If one method in a struct requires a pointer receiver, it's recommended to make all methods in that struct use pointer receivers. This ensures consistency in the method set, regardless of whether the receiver is a value or a pointer.

By applying these recommendations, you can eliminate the issue of field values reverting in your Go program.

以上是為什麼我的 Go struct 欄位修改後會恢復為原始值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板