如何取消引用作为空接口传递的指针值? [英] How do i dereference a pointer value passed as the empty interface?

查看:112
本文介绍了如何取消引用作为空接口传递的指针值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法对我用于数据库访问的类型采用target interface{}:

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

然后这样称呼

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

在传递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.

如果我不需要通过interface{},我可以想象它是这样完成的:

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
}

如果我尝试使用实际签名执行相同操作,则无法像这样取消引用target中包含的值:

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?

推荐答案

您可以使用'reflect'包来做到这一点.

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

这篇关于如何取消引用作为空接口传递的指针值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆