我想创建一个函数(在名为Successfully started Solr ...
rake aborted!
Sunspot::Solr::Server::AlreadyRunningError: Server is already running with PID 38712
的示例代码中),该函数接受任意结构并填充数据库查询中的值。请注意"属性" GremlinResultStruct中的键也是任意的(这就是为什么它是RAILS_ENV=test rake sunspot:solr:stop
rake aborted!
Sunspot::Solr::Server::NotRunningError: Process with PID 38926 is no
longer running
)
目标:
我希望gremlinResultToStruct()
根据其密钥填充给定的结构,如果它们在数据库结果中可用的话。
为什么:
我的代码库中有数百个像Foo和Bar这样的结构体,我希望有一个函数来填充代码中所需的结构,而不是创建半重复的代码。
CODE:
我的代码看起来像这样,它还包含以下问题:
Properties map[string][]struct
示例JSON结果。
结果-A:
gremlinResultToStruct()
结果-B:
// Gremlin Query result struct
type GremlinResult struct {
AtType string `json:"@type"`
AtValue []struct {
AtType string `json:"@type"`
AtValue struct {
ID struct {
AtType string `json:"@type"`
AtValue int `json:"@value"`
} `json:"id"`
Label string `json:"label"`
Properties map[string][]struct { // <== IMPORTANT, CONTAINS A VALUE THAT IS THE EQUIVALENT OF THE KEY IN THE STRUCT (like Something, SomethingElse, EvenMoreSomethingElse or AndMoreSomethingElse)
AtType string `json:"@type"`
AtValue struct {
ID struct {
AtType string `json:"@type"`
AtValue int `json:"@value"`
} `json:"id"`
Label string `json:"label"`
Value string `json:"value"`
} `json:"@value"`
} `json:"@properties"`
} `json:"@value"`
} `json:"@value"`
}
type Foo struct {
Something string
SomethingElse bool
}
type Bar struct {
EvenMoreSomethingElse string
AndMoreSomethingElse int
}
func gremlinResultToStruct(result *GremlinResult, ???){ // What to do at ???
// How to itterate over the ??? key values (like: Something, SomethingElse, EvenMoreSomethingElse or AndMoreSomethingElse)
// How to populate:
// VARIABLE := Something, SomethingElse, EvenMoreSomethingElse or AndMoreSomethingElse
// result.AtValue[0].AtValue.Properties[ VARIABLE ][0].AtValue.Value
}
func main {
// Do stuff to get JSON results. HOW is not relevant for question
dbResults := doDbStuffToPopulateResuts()
// Create the results variable as gremlinResults struct
results := GremlinResult{}
// Unmarshall to this struct
err = json.Unmarshal(dbResults, &results)
// 1. Expected result should be "result-a" (see below)
// Create the Foo struct
foo := Foo{}
// HERE IS MY QUESTION ABOUT (see function above)
gremlinResultToStruct(&results, &foo)
// NOW foo SHOULD HAVE Something and SomethingElse set
fmt.Println(foo.Something, foo.SomethingElse)
// 2. Expected result should be "result-b" (see below)
// Create the Bar struct
bar := Bar{}
// HERE IS MY QUESTION ABOUT (see function above)
gremlinResultToStruct(&results, &bar)
// NOW foo SHOULD HAVE Something and SomethingElse set
fmt.Println(bar.EvenMoreSomethingElse, bar.AndMoreSomethingElse)
}