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

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误