2015-11-05 69 views
1

我有一個結構,我將所有小時和分鐘存儲到mongodb中。在這種情況下,當我收到修改該值的請求時,我將字符串作爲小時和分鐘。有沒有辦法從被給出作爲輸入將字符串轉換爲字段名稱

字符串中找到字段名你可以看到它here

package main 

import "fmt" 

type Min struct { 
    v01 int `bson:"01",json:"01"` 
    v02 int `bson:"02",json:"02"` 
} 

type Hour struct { 
    v01 Min `bson:"01",json:"01"` 
    v02 Min `bson:"02",json:"02"` 
} 

func main() { 
    fmt.Println("Hello, playground") 
    var h Hour 
    h.v01.v01 = 1 
    h.v02.v01 = 2 
    fmt.Println(h) 
    h.Set("01", "01", 10) 
    fmt.Println(h) 
} 

func (h *Hour) Set(hour string, min string, value int) { 
    h.v01.v01 = 10 //Here I have hardcoded it 
    // Is there a way to do this from the given input 
    // e.g. h.Set("01","01",100) 
} 

如果您發現,輸入爲"01","01"。我想將此輸入更改爲h.v01.v01。 Go有可能嗎?

注:我在這種情況下目前使用maps。如果可能的話,我想將其改爲結構訪問,以便我可以使用goroutine來加速我的程序。目前goroutines不適合寫入地圖。

+5

夠程是不是安全的同時寫*什麼*。無論您是否有地圖或結構,都需要同步訪問權限。 – JimB

+0

[GoLang:按名稱訪問struct屬性]的可能重複(http://stackoverflow.com/questions/18930910/golang-access-struct-property-by-name) –

回答

0

目前goroutines對寫入地圖是不安全的。

這可能需要與圍棋1.9(2017年8月)上重新和concurrent map存在於sync package

Map類型在sync封裝與攤銷-恆併發地圖時間加載,存儲和刪除。
多個goroutines同時調用Map的方法是安全的。

再加上我在「GoLang: Access struct property by name」提到,作爲評價,oleiade/reflections,你應該能夠做到兩者(訪問屬性名稱,並使用地圖)