您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

您如何在Go运行时根据其类型创建结构的新实例?

您如何在Go运行时根据其类型创建结构的新实例?

为了做到这一点,你需要reflect

package main

import (
    "fmt"
    "reflect"
)

func main() {
    // one way is to have a value of the type you want already
    a := 1
    // reflect.New works kind of like the built-in function new
    // We'll get a reflected pointer to a new int value
    intPtr := reflect.New(reflect.TypeOf(a))
    // Just to prove it
    b := intPtr.Elem().Interface().(int)
    // Prints 0
    fmt.Println(b)

    // We can also use reflect.New without having a value of the type
    var nilInt *int
    intType := reflect.TypeOf(nilInt).Elem()
    intPtr2 := reflect.New(intType)
    // Same as above
    c := intPtr2.Elem().Interface().(int)
    // Prints 0 again
    fmt.Println(c)
}

您可以使用结构类型(而不是int)执行相同的操作。还是其他的,真的。只需确保了解map和slice类型时new和make之间的区别即可。

Go 2022/1/1 18:13:54 有617人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶