登录
首页 >  Golang >  Go问答

利用反射技术如何确定片段的数据类型?

来源:stackoverflow

时间:2024-02-28 21:03:25 482浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《利用反射技术如何确定片段的数据类型?》,聊聊,我们一起来看看吧!

问题内容

我想填充切片数据,但使用reflect.kind()只能让我知道field(0)是切片, 但我不知道它是什么类型的切片,它可能是 int[] 或 string[] 或其他类型的切片

在我知道切片数据类型是什么之前,仓促设置值会panic,有人知道如何获取切片类型信息吗?

func WhatSlice(isAny any) {
    vof := reflect.ValueOf(isAny)
    if vof.Kind() != reflect.Struct {
        return
    }
    switch vof.Field(0).Kind() {
    case reflect.Slice:
        for i := 0; i < vof.Field(0).Len(); i++ {
            // how to know this field is []int or []string?
            // vof.Field(0).Index(i).Set()
        }
    default:
        return
    }
}

正确答案


使用type可以直接获取切片类型 但应该使用字符串类型来区分。

func whatslice(isany any) {
    vof := reflect.valueof(isany)

    if vof.kind() != reflect.struct {
        return
    }

    switch vof.field(0).kind() {
    case reflect.slice:
        switch vof.field(0).type().string() {
        case "[]int":
            fmt.println("int here")
        case "[]string":
            fmt.println("string here")
        }
    default:
        return
    }
}

您可以在调用 for 循环之前使用 vof.field(0).index(0).kind() 进行检查

func WhatSlice(isAny any) {
    vof := reflect.ValueOf(isAny)
    if vof.Kind() != reflect.Struct {
        return
    }
    switch vof.Field(0).Kind() {
    case reflect.Slice:
        if vof.Field(0).Len() == 0 {
            fmt.Println("empty slice")
            return
        }
        switch vof.Field(0).Index(0).Kind() {
        case reflect.Int:
            fmt.Println("int here")
            // for i := 0; i < vof.Field(0).Len(); i++ {
            // how to know this field is []int or []string?
            // vof.Field(0).Index(i).Set()
            // }
        case reflect.String:
            fmt.Println("string here")
        }
    default:
        return
    }
}

playground

到这里,我们也就讲完了《利用反射技术如何确定片段的数据类型?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>