douli8428 2018-03-28 17:05
浏览 45
已采纳

如何取消引用作为空接口传递的指针值?

I've got a method taking a target interface{} on a type that I use for database access like:

func (c *client) Query(query someType, target interface{}) error {
    return c.db.Query(query).Decode(target)
}

This is then called like

result := resultType{}
if err := c.Query(myQuery, &result); err == nil {
    // do sth with result
}

Which does what I want it do as I am passing the pointer address of result

The trouble I am now running into is that I do not know how I can mock this kind of behavior (mutating the passed reference) in a test.

In case I wouldn't need to pass interface{} I could imagine it being done like this:

type mockClient struct {
    targetValue resultType
}

func (m *mockClient) Query(query someType, target *resultType) error {
    *target = m.targetValue
    return nil
}

If I try to do the same using my actual signature, I am not able to dereference the value contained in target like this:

type mockClient struct {
    targetValue interface{}
}

func (m *mockClient) Query(query someType, target interface{}) error {
    target = m.targetValue // this does not mutate the passed target
    return nil
} 

Can I dereference a pointer value when it is passed in as the empty interface? In case it is not possible, what would be another approach of testing the side effects my method has without having to resort to concrete types as arguments?

  • 写回答

1条回答 默认 最新

  • dtxq82489 2018-03-29 10:03
    关注

    You can use 'reflect' package to do it.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type mockClient struct {}
    
    func (m *mockClient) Query(query string, target interface{}) error {
        a := "changed"
        va := reflect.ValueOf(a)
        reflect.ValueOf(target).Elem().Set(va)
        return nil
    }
    
    func main() {
        var mc mockClient
        target := "initial"
        mc.Query("qwe", &target)
        fmt.Println(target)
    }
    

    The simple example to reference you can find here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog