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

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

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效