【问题标题】:Instantiate a new obj using Go reflect and type assert to an interface使用 Go reflect 实例化一个新的 obj 并将 assert 类型输入到一个接口
【发布时间】:2020-05-26 10:36:49
【问题描述】:

我无法解释为什么以下内容有效。

package main

import (
    "fmt"
    "reflect"
    "strings"
)

type MyInterface interface {
    someFunc()
}

type Dock struct {
}

func (d *Dock) someFunc() {
}

type Group struct {
    Docks []Dock `better:"sometag"`
}

func foo(model interface{}) {
    v1 := reflect.Indirect(reflect.ValueOf(model))
    for i := 0; i < v1.NumField(); i++ {
        tag := v1.Type().Field(i).Tag.Get("better")
        if strings.HasPrefix(tag, "sometag") {
            inter := v1.Field(i).Interface()
            typ := reflect.TypeOf(inter).Elem()
            fmt.Println("Type:", typ.String())

            // Want to instantiate type like &Dock{} then assign it to some interface,
            // but using reflect
            n := reflect.New(typ)
            _, ok := n.Interface().(MyInterface)            
            fmt.Println("Why is it OK?", ok)

        }
    }
}

func main() {
    g := &Group{}
    foo(g)

    /*var v1, v2 interface{}
    d1 := &Dock{}
    v1 = d1
    _, ok1 := v1.(MyInterface)

    d2 := Dock{}
    v2 = d2
    _, ok2 := v2.(MyInterface)
    fmt.Println(ok1, ok2)*/
}

打印出来

Type: main.Dock
OK? true

如果它是一个 Dock 类型,那么它就不是一个指向 Dock 的指针。为什么符合MyInterface

https://play.golang.org/p/Z9mR8amYOM7

评论中的 d2 示例没有。

【问题讨论】:

  • go doc reflect.New: "New 返回一个Value,表示一个指针指向指定类型的新零值。也就是说,返回的Value的Type是PtrTo(typ )。”总是,从字面上看总是阅读文档。

标签: go go-reflect


【解决方案1】:

go docreflect.New

New 返回一个 Value,表示指向新零值的指针 指定类型。即返回Value的Type是PtrTo(typ)。

n := reflect.New(typ)
fmt.Println("Type:", n.String())

它将打印Type: &lt;*main.Dock Value&gt; 表示nDock 的指针。您错过了使用reflect.New 返回指针的部分。

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2022-01-17
    • 2021-08-13
    • 2016-11-16
    相关资源
    最近更新 更多