登录
首页 >  Golang >  Go问答

尝试在使用空接口参数进行数据返回时遇到问题

来源:stackoverflow

时间:2024-02-24 14:00:25 138浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《尝试在使用空接口参数进行数据返回时遇到问题》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我正在尝试通过添加缓存来编写一个使用 interface{} 参数返回数据的函数的包装。

我的问题是,一旦我有了有效的 interface{},我不知道如何将其指定为在参数中返回。包装后的调用是 github api 客户端中的 (github.client) .do ,当我尝试使用 go-cache 添加缓存时,问题出现了

这有点是我的职责

func (c *cachedclient) requestapi(url string, v interface{}) error {
    x, found := c.cache.get(url)
    if found {                        // found in cache code
        log.printf("cached: %v", x)
        v = x // here: this do not work. x contains a valid copy of what i want but how do i store it in v?
        return nil
    }
    req, _ := c.githubclient.newrequest("get", url, nil)    // not found i cache, request it
    res, err := c.githubclient.do(*c.context, req, v)
    if err != nil {
        return err
    }
    if res.statuscode != 200 {
        return fmt.errorf("error getting %v: %v", url, res.status)
    }
    c.cache.add(url, v, cache.defaultexpiration)   // store in cache
    return nil    // once here v works as expected and contain a valid item
}

当我尝试像这样使用它时必须返回缓存值时会失败:

// Some init code c is a cachedClient 
i := new(github.Issue)

c.requestAPI(anAPIValidURLforAnIssue, i)
log.Printf("%+v", i)    // var i correctly contains an issue from the github api

o := new(github.Issue)
c.requestAPI(anAPIValidURLforAnIssue, o)
log.Printf("%+v", o)  // var o should have been get from the cache but here is empty

所以基本上我的问题是,当我正确恢复缓存的项目时,它很好,但我无法将其存储在用于存储它的参数中。我无法使用子类,因为我正在包装的调用已经使用 interface{}。我无法将其移至返回值,因为您无法返回通用接口。如何将 interface{} x 存储在 v 中以使其在外部可用?


解决方案


要归档您想要的内容,您需要使用一些反射魔法。 请尝试将 v = x 替换为下一个代码片段:

reflect.valueof(v).elem().set(reflect.valueof(x).elem())

op 的注释:我必须添加最后一个 .elem() 才能完成这项工作。

注意:在调用 requestapi 方法时,您应该使用指向该值的指针: 假设缓存值的类型为 int。然后你应该像这样调用 requestapi

var dst int // destination of the cached value or a newly retrieved result
cc.requestapi(url, &dst)

在某些假设下,例如您将 json 数据存储在缓存中,下面是我将尝试的方法。错误未处理。

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)
}

其实上面就是githubclient.do也在做的事情。它检查 v 是否满足 io.writer 接口,如果满足,则将数据写入 v。如果不满足,则将 json 解组到 v,如上所示。所以同样可以从缓存中完成。

在这里检查: https://github.com/google/go-github/blob/v32.1.0/github/github.go#L586

如果缓存对象是特定的,则可以使用以下内容。您不处理空接口{},因为您应该能够将特定类型作为 v 传递给 c.githubclient.do 。由于它使用 json 包,因此它将检测类型信息并相应地将值填充到其中。 假设您存储 type 数据结构

在下面的代码中,消除了其他细节,例如条件检查是否缓存和错误处理

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)
}

好了,本文到此结束,带大家了解了《尝试在使用空接口参数进行数据返回时遇到问题》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>