2017-06-24 9 views
-1

私はGoで新しく、構造体関数でポインタを使用しないと構造体フィールド値が書き込まれない理由を理解できません。ここでは例の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

に説明されていることhttps://tour.golang.org/methods/4助けない、またはあなたはまだreadi後に質問がありますかそれ? – smarx

+2

そのページの最も重要な部分: "値受信側では、Scaleメソッドは元のVertex値のコピーに対して動作します(これは他の関数引数と同じ動作です)。" – smarx

+0

@smarxありがとうございます実際に何が起こるかについて私の疑問をすべて解決するわけではありません。正確にはどういう意味ですか?「値受信機では、Scaleメソッドは元の頂点値のコピーで動作します。」これは、構造体の新しいインスタンスが即座に作成され、元のインスタンスのすべてのフィールドが再帰的に複製されることを意味しますか?だから、巨大なオブジェクトがバリューレシーバとして渡された場合、利用可能なすべてのメモリを満たすことができますか? –

答えて

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

関連する問題