加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

反射 – 如何使用反射在golang中使用给定名称(字符串)创建数组

发布时间:2020-12-16 09:27:14 所属栏目:大数据 来源:网络整理
导读:我想在golang中使用name创建数组,但是我遇到了一些错误 这是我的代码 包主 import ( "fmt" "reflect")type My struct{ Name string Id int}func main() { my := My{} myType := reflect.TypeOf(my) fmt.Println(myType) //v := reflect.New(myType).Elem().I
我想在golang中使用name创建数组,但是我遇到了一些错误
这是我的代码
包主

import (
    "fmt"
    "reflect"
)

type My struct{
    Name string
    Id int
}

func main() {
    my := &My{}
    myType := reflect.TypeOf(my)
    fmt.Println(myType)
    //v := reflect.New(myType).Elem().Interface()

    // I want to make array  with My
    //a := make([](myType.(type),0)  //can compile
    //a := make([]v.(type),0)  ////can compile
    fmt.Println(a)
}

解决方法

我相信这就是你要找的东西:

slice := reflect.MakeSlice(reflect.SliceOf(myType),0).Interface()

工作范例:

> http://play.golang.org/p/jiYluu52ae

作为旁注,在大多数情况下,零切片比容量为零的切片更合适.如果你想要一个零切片,那么这样做:

slice := reflect.Zero(reflect.SliceOf(myType)).Interface()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读