2 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
要?dú)w檔您想要的內(nèi)容,您需要使用一些反射魔法。請(qǐng)嘗試v = x用下一個(gè)代碼段替換:
reflect.ValueOf(v).Elem().Set(reflect.ValueOf(x).Elem())
來(lái)自 OP 的注釋:我必須添加最后一個(gè).Elem()才能完成這項(xiàng)工作。
注意:在調(diào)用該requestAPI方法時(shí),您應(yīng)該使用指向該值的指針:假設(shè)緩存的值是 type int。然后你應(yīng)該requestAPI像這樣打電話:
var dst int // destination of the cached value or a newly retrieved result
cc.requestAPI(url, &dst)

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
在某些假設(shè)下,例如您將 json 數(shù)據(jù)存儲(chǔ)在下面的緩存中,我將嘗試這樣做。錯(cuò)誤未處理。
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Name string
}
func main() {
var d Data
requestAPI(&d)
fmt.Println(d)
}
func requestAPI(v interface{}) {
var cache_res interface{} = []byte("{\"Name\":\"CCC\"}")
//assume you got cache_res from cache
x, _ := cache_res.([]byte)
_ = json.Unmarshal(x, &v)
}
其實(shí)上面githubClient.Do也是在做的。它檢查 v 是否滿足io.Writer接口,如果是,則將數(shù)據(jù)寫入 v。如果不是,則將 json 解組到 v 中,如上所示。所以同樣可以從緩存中完成。
在這里查看: https ://github.com/google/go-github/blob/v32.1.0/github/github.go#L586
如果緩存對(duì)象是特定的,則可以使用以下內(nèi)容。您不處理空接口{},因?yàn)槟鷳?yīng)該能夠?qū)⑻囟愋蛡鬟f給c.githubClient.Doas v。由于它使用 json 包,它將檢測(cè)類型信息并相應(yīng)地將值填充到其中。假設(shè)您存儲(chǔ)type Data struct
在下面的代碼中,消除了其他細(xì)節(jié),例如條件檢查是否緩存和錯(cuò)誤處理
package main
import (
"fmt"
)
type Data struct {
Name string
}
func main() {
var d Data
requestAPI(&d)
fmt.Println(d)
}
func requestAPI(v *Data) {
var cache_res interface{} = Data{"CCC"}
//assume you got cache_res from cache
x, _ := cache_res.(Data)
*v = x
//in case you did not find it in cache then githubClient.Do should unmarshal
//contents of response body into v *Data if Data fields match that of json
//res, err := c.githubClient.Do(*c.context, req, v)
}
- 2 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報(bào)