Home >Backend Development >Golang >Why Does My Go Struct Field Revert After a Method Call?

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

DDD
DDDOriginal
2024-11-15 05:48:02346browse

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.

The above is the detailed content of Why Does My Go Struct Field Revert After a Method Call?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn