doucha7329 2016-08-07 21:54
浏览 110
已采纳

从反射类型创建切片

I am trying to create a slice from a reflect.Type. This is what I have so far.

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.New(reflect.SliceOf(elemType)).Interface()

    elemSlice = append(elemSlice, TestStruct{"Testing"})

    fmt.Printf("%+v
", elemSlice)

}

However I get the following error and I'm not sure how to get around it without hardcoding a conversion to []TestStruct.

prog.go:17: first argument to append must be slice; have interface {}

Is there anyway to treat the returned interface as a slice without having to hardcode the conversion from interface{} to []TestStruct?

  • 写回答

2条回答 默认 最新

  • douyong7199 2016-08-07 22:23
    关注

    No, what you describe is not possible. Not type asserting the result of .Interface() limits what you can do. Your best chance is to continue to work with the reflect.Value value:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type TestStruct struct {
        TestStr string
    }
    
    func main() {
        elemType := reflect.TypeOf(TestStruct{})
    
        elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
    
        elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
    
        fmt.Printf("%+v
    ", elemSlice)
    
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集