去,在函数中写结构字段

时间:2017-06-24 10:11:27

标签: go struct

我是Go的新手,如果我不在结构函数中使用指针,我就不明白为什么不写入struct字段值。这里有一个例子,当调用setValue()时,它会执行但是没有设置值:

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\n")
    obj.setValue("setValue_Called")
    fmt.Printf("obj.getValue()        = [%v]\n", obj.getValue())
    fmt.Printf("obj.getValuePointer() = [%v]\n", obj.getValuePointer())

    fmt.Printf("Use setValuePointer function\n")
    obj.setValuePointer("setValuePointer_Called")
    fmt.Printf("obj.getValue()        = [%v]\n", obj.getValue())
    fmt.Printf("obj.getValuePointer() = [%v]\n", obj.getValuePointer())
}

此代码打印:

Use setValue function
obj.getValue()        = [initValue]
obj.getValuePointer() = [initValue]
Use setValuePointer function
obj.getValue()        = [setValuePointer_Called]
obj.getValuePointer() = [setValuePointer_Called]

当使用或不使用指针创建struct函数时,有人可以帮助我理解在幕后发生的事情吗? 另外,setValue在没有错误或警告的情况下执行这一事实对我来说非常害怕:(

1 个答案:

答案 0 :(得分:1)

在定义方法时要记住的一件事是:

方法就像普通函数一样,当你调用setValue()函数时,会发生什么。

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.

gotour

清楚解释了这一点