gout 使用笔记2

目前对于反射使用不是很熟悉,记录之

复制代码
if val.Kind() == reflect.Interface {
            val = reflect.ValueOf(val.Interface())
  }
switch t := val.Kind(); t {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
---------------------------------------

if val.Kind() == reflect.Interface {
            val = val.Elem()-----??????
 }
switch val.Kind() {
case reflect.Slice, reflect.Array:
 
复制代码

接口类型取值其类型是啥?

具体查看:go  里面的/src/reflect/value.go

  1. 调用 reflect.ValueOf 获取变量指针;
  2. 调用 reflect.Value.Elem 获取指针指向的变量;
  3. 调用 reflect.Value.SetInt 更新变量的值:
复制代码
import (
    "fmt"
    "reflect"
)
type st struct {
    a int
    b string
}


func main() {
    var num interface{} = 44

    val := reflect.ValueOf(num)

    if val.Kind() == reflect.Interface {
        val = val.Elem()
        fmt.Println("is Interface ")
    }

    fmt.Println("Kind:", val.Kind()) // Output: Kind: int
    fmt.Println("Value:", val.Int()) // Output: Value: 42
    ptr := &num
     val = reflect.ValueOf(ptr)
    if val.Kind() == reflect.Ptr {
        fmt.Println("is ptr ")
        // Get the underlying element of the pointer
        elemVal := val.Elem()

        // Check if elemVal is an interface
        if elemVal.Kind() == reflect.Interface {
            elemVal = elemVal.Elem()
            //上面一句elemVal = elemVal.Elem() 有没有无所谓    Get the underlying concrete value of the interface
            concreteVal := elemVal.Interface()
            fmt.Println("Underlying concrete value:", concreteVal) // Output: Underlying concrete value: 42
        }
    }
    // Create a reflect.Value for ptr
    val = reflect.ValueOf(ptr)
   var a interface{}
    //a = st{a:10, b:"hello"}
    a = []int{1,2,3}
    v := reflect.ValueOf(a)
    fmt.Println(v)
    fmt.Println(v.Index(1).Interface())
    k := v.Kind()
    fmt.Println(k)
}
/*
Kind: int
Value: 44
is ptr 
Underlying concrete value: 44
[1 2 3]
2
slice
*/
复制代码

 

posted @   codestacklinuxer  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2021-08-01 redis:字典-hash
点击右上角即可分享
微信分享提示