首頁 > 後端開發 > Golang > 為什麼我的 Go 結構體欄位在方法呼叫後會恢復?

為什麼我的 Go 結構體欄位在方法呼叫後會恢復?

DDD
發布: 2024-11-15 05:48:02
原創
369 人瀏覽過

Why Does My Go Struct Field Revert After a Method Call?

Struct Field Reverting

In the provided Go code, a strange behavior is observed where a struct field changes within a method but reverts to its original value when checked afterward. This issue stems from the fact that the struct is being passed by value instead of by pointer.

Explanation:

In the sendMessage method of the TVManager struct, a method sendCommand of a connector struct is called with a value of the TVManager struct. When a struct is passed by value, a copy of the struct is created and passed instead of a reference to the original struct.

In the sendCommand method of the MockConnector struct, the fields of the connector struct (e.g., last_command, value) are modified. However, since the connector is being passed by value, the modifications are only applied to the copy of the struct, not the original one.

To resolve this issue, the connector struct in the sendCommand method should be passed by pointer instead of by value. This allows the method to modify the original connector struct, rather than a copy.

Solution:

Replace:

func (this MockConnector) sendCommand(payload map[string]string)
登入後複製

With:

func (this *MockConnector) sendCommand(payload map[string]string)
登入後複製

Additional Considerations:

  • It's generally discouraged to use "this" as a receiver name in Go.
  • If one method of a given type requires a pointer receiver, it's best practice to use pointer receivers for all methods of that type.

以上是為什麼我的 Go 結構體欄位在方法呼叫後會恢復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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