2017-08-25 60 views
0

我與圍棋打了一下,卻發現這個奇怪的情況,同時做一些測試。結構現場恢復

我使用的方法在一個結構的變量發送到應該改變字段的另一種方法,但是當我在最後檢查,本場回到第一個值,其中有我的困惑。

func (this TVManager) sendMessage(message string) { 
    fmt.Println("5", this.connector) 
    payload := map[string]string { 
     "id": "0", 
     "type": "request", 
     "uri": "ssap://system.notifications/createToast", 
     "payload": "{'message': 'This is a message'}"} 
    this.connector.sendCommand(payload) 
    fmt.Println("4", this.connector) 
} 

這是我測試的方法,它調用連接器的sendCommand。

func (this MockConnector) sendCommand(payload map[string]string) { 
    fmt.Println("0", this) 
    this.last_command = payload 
    this.value = true 
    fmt.Println("0", this) 
} 

我在使用的模擬對象中的哪個只是簡單地改變了這個struct字段的值。

manager.sendMessage("This is a message") 

fmt.Println("1", connector) 
assert.Equal(t, expected, connector.last_command, "Command should be equal") 

但是,當我檢查它,它會回到內部。我設置了一些打印以嘗試d跟蹤值,並且他們按預期改變了這些值,但隨後它會恢復。

1 {false map[]} 
5 {false map[]} 
0 {false map[]} 
0 {true map[uri:ssap://system.notifications/createToast payload:{'message': 'This is a message'} id:0 type:request]} 
4 {false map[]} 
1 {false map[]} 
--- FAIL: TestTVManagerSendsNotificationDownToConnector (0.00s) 

這只是一個小程序,我要去學習一些Go,所以我很感謝任何人都可以給我的幫助。

回答

2

您是按值傳遞的結構。只要你不修改結構,這工作正常,但如果你修改它,你實際上只是修改一個副本。爲了使這項工作,你需要使用指針到你需要修改的結構。

相反的:

func (this MockConnector) sendCommand(payload map[string]string) 

用途:

func (this *MockConnector) sendCommand(payload map[string]string) 

此外,它被認爲是一個壞主意,用this(或self)在圍棋接收器的名字,作爲一個接收器不與其他語言中的指針/引用this相同。

另一個最佳實踐,是如果對於給定類型的一種方法需要一個指針接收器,該類型的所有方法應具有指針接收器。這樣,無論該值是否爲指針,方法集都保持一致。

請參閱method setstheseFAQanswers瞭解更多信息。

+0

謝謝,我在想,它有什麼做這一點,但嘗試將指針傳遞給這樣的FUNC(這MockConnector)sendCommand(*有效載荷地圖[字符串]字符串)。我現在是未來的實際有效載荷Python背景所以指針是我需要習慣的東西。 – cllamach

+0

我也可以使用任何接收器名稱?接收器沒有預期的社區良好代碼名稱?這是某種方式......解放。謝謝你的幫助。 – cllamach

+0

使用任何你想要的,在這種情況下,我會用'mock'或'conn'或類似的東西,但是這只是我...一個好的經驗法則是假裝它是一個參數挑選名稱時。 –