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 :(
One thing to remember while you were defining methods is:
Methods are like normal functions, and when you were calling setValue()
function, what's happening is this.
package main
import "fmt"
type vertex struct {
x int
y int
}
func main() {
var v vertex
fmt.Println(v.setVertex(1, 2))
fmt.Println(v)
/* v = v.setVertex(1,2)
// we are assigning the returned variable address to v.
fmt.Println(v)
*/
}
// With a value receiver, the setVertex method operates on a copy of the
// original vertex value. (This is the same behavior as for any other
// function argument.)
// This methods has a value as a reciver, so it gets the copy not the
// original vertex.
func (v vertex) setVertex(x, y int) vertex {
// Here it is similar to creating a new variable with name 'v',
// Go is lexically scoped using blocks, so this variable exists only
// in this block, while it is returned we are printing it but we didn't
// store it in another variable.
v.x = x
v.y = y
return v
}
// If you want to change any variable or struct, we need to pass its
// address, else only copy of that variable is received by the called
// function.
This is clearly explained in gotour