I am new in Go and I don't understand why the struct field values are not written if I don't use a pointer in the struct functions. Here an example, when setValue() is called, it executes but the value is not set:
type myStruct struct {
value string
}
func (m myStruct) getValue() string { return m.value }
func (m myStruct) setValue(val string) { m.value = val }
func (m *myStruct) getValuePointer() string { return m.value }
func (m *myStruct) setValuePointer(val string) { m.value = val }
func TestStruct(t *testing.T) {
obj := myStruct{value: "initValue"}
fmt.Printf("Use setValue function
")
obj.setValue("setValue_Called")
fmt.Printf("obj.getValue() = [%v]
", obj.getValue())
fmt.Printf("obj.getValuePointer() = [%v]
", obj.getValuePointer())
fmt.Printf("Use setValuePointer function
")
obj.setValuePointer("setValuePointer_Called")
fmt.Printf("obj.getValue() = [%v]
", obj.getValue())
fmt.Printf("obj.getValuePointer() = [%v]
", obj.getValuePointer())
}
this code prints:
Use setValue function
obj.getValue() = [initValue]
obj.getValuePointer() = [initValue]
Use setValuePointer function
obj.getValue() = [setValuePointer_Called]
obj.getValuePointer() = [setValuePointer_Called]
Could someone help me understanding what happens under the hood when a struct function is created using or not using a pointer? In addition, the fact that setValue executes with no errors or warnings is quite scaring to me :(