简体   繁体   English

如何使用反射在 go 中创建接口值类型的 object

[英]How to create an object of interface value type in go using reflection

UPDATED更新

I want to make helper function for testing reading env vars function.我想制作助手 function 来测试读取环境变量 function。 It uses envconfig .它使用envconfig

func Test_T2(t *testing.T) {

    os.Setenv("APP_PARAM_STR", "string value")
    os.Setenv("APP_PARAM_INT", "12")

    os.Setenv("APP_PARAM_DURATION", "15s")
    os.Setenv("APP_PARAM_INT", "44")

    c := ConfigTwo{}

    d := ConfigTwo{
        ParamDuration: 15*time.Second,
        ParamInt:      44,
    }

    helper(t, &c, &d)
}

func helper(t *testing.T, confObject, expValue interface{}) {
    t.Helper()

    err := getParams(&confObject)
    if !assert.NoError(t, err) {
        return
    }

    assert.Equal(t, expValue, confObject)
}

func getParams(cfg interface{}) error {
    return envconfig.Process("APP", cfg)

}

** UPDATE 2 **
It works. Thanks everyone.

It works if I have getPrams function only.如果我只有 getPrams function,它就可以工作。 But if I add helper (that I need to test different structs) I get an error: specification must be a struct pointer但是如果我添加助手(我需要测试不同的结构)我会得到一个错误: specification must be a struct pointer

envconfig performs two checks here : envconfig这里执行两项检查:

Use this code.使用此代码。 The argument is a pointer to the expected value.参数是一个指向期望值的指针。

func helper(t *testing.T, pexpected interface{}) {
    t.Helper()
    pactual := reflect.New(reflect.TypeOf(pexpected).Elem()).Interface()

    err := getParams(pactual)
    if !assert.NoError(t, err) {
        return
    }

    assert.Equal(t, pexpected, pactual)
}

The expression reflect.New(reflect.TypeOf(pexeceted).Elem()).Interface() returns a pointer to a new empty value with the same type as what pexpected points to.表达式reflect.New(reflect.TypeOf(pexeceted).Elem()).Interface()返回一个指向与 pexpected 指向的类型相同的新空值的指针。

Call it like this:像这样称呼它:

helper(t, &ConfigTwo{A: "expected A Field", B: "expected B field"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM