zoukankan      html  css  js  c++  java
  • golang 反射

      Golang的指定类型的变量的类型是静态的(也就是指定int、string这些的变量,它的type是static type),在创建变量的时候就已经确定,有静态那么有没有动态呢??

      说起动态目前也就只能想起 接口Interface;在Golang的实现中,每个interface变量都有一个对应pair,pair中记录了实际变量的值和类型:(value, type)--value是实际变量值,type是实际变量的类型。一个interface{}类型的变量包含了2个指针,一个指针指向值的类型【对应concrete type】,另外一个指针指向实际的值【对应value】。

    什么是反射?

    --->反射就是程序能够在运行时检查变量和值,求出它们的类型??------什么意思----??自古以来越是简单描述的东西越难懂,但是理解后又是豁然开朗。

    在 Golang中,reflect 实现了运行时反射。reflect 包会帮助识别 interface{} 变量的底层具体类型和具体值。

    reflect.Type 和 reflect.Value

    reflect.Type 表示 interface{} 的具体类型,而 reflect.Value 表示它的具体值。reflect.TypeOf()reflect.ValueOf() 两个函数可以分别返回 reflect.Typereflect.Value。这两种类型是我们创建查询生成器的基础;

    reflect 包中还有一个重要的类型:Kind

    在反射包中,KindType 的类型可能看起来很相似,

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type order struct {
        ordId      int
        customerId int
    }
    
    func createQuery(q interface{}) {
        t := reflect.TypeOf(q)
        v := reflect.ValueOf(q)
        fmt.Println("Type ", t)
        fmt.Println("Value ", v)
    
    
    }

    func createQuery_kind(q interface{}) {
        t := reflect.TypeOf(q)
        k := t.Kind()
        fmt.Println("Type ", t)
        fmt.Println("Kind ", k)


    }

    func main() { o :
    = order{ ordId: 456, customerId: 56, } createQuery(o) } -----------------------------------结果--- Type main.order Value {456 56}

    Type  main.order
    Kind  struct

    NumField() 和 Field() 方法

    NumField() 方法返回结构体中字段的数量,而 Field(i int) 方法返回字段 ireflect.Value

    Int() 和 String() 方法

    IntString 可以帮助我们分别取出 reflect.Value 作为 int64string

  • 相关阅读:
    Redis到底该如何利用?
    AutoMapper搬运工之自定义类型转换
    AutoMapper搬运工之初探AutoMapper
    【ELK】docker-compose搭建ELK单机环境
    [flowable工作流引擎]基本概念及术语
    shell遍历文件夹读取文件夹下的文件
    vector类的简单实现
    string类的实现
    接口安全认证
    C# lock private VS private static
  • 原文地址:https://www.cnblogs.com/codestack/p/13574505.html
Copyright © 2011-2022 走看看