zoukankan      html  css  js  c++  java
  • golang reflect 简单使用举例

    golang中的多态,主要由接口interface体现。

    接口interface在实现上,包括两部分:动态类型和动态值。

    golang提供的reflect包可以用来查看这两部分。

    动态类型

    func TypeOf(i interface{}) Type
    

    返回i的动态类型。

    动态值

    func ValueOf(i interface{}) Value
    

    返回i存放的动态值。

    下面举例说明。

    package main
    
    import (
            "fmt"
            "reflect"
    )
    
    
    func main(){
    
            count := 99
    
            refType := reflect.TypeOf(count)
            fmt.Println("Type reflect.TypeOf():", refType) // reflect.TypeOf()
    
            refValue := reflect.ValueOf(count)
            fmt.Println("reflect.ValueOf():", refValue) // reflect.ValueOf()
    
            fmt.Println("Type Value.Type():", refValue.Type()) // equal to reflect.TypeOf()
    
            // basic type
            fmt.Println("basic type, Kind():", refValue.Kind())
    
            fmt.Println("value.Int():", refValue.Int())
            fmt.Println("value.Interface():", refValue.Interface())
            fmt.Println("value.Interface().(int):", refValue.Interface().(int)) // assert type
    }
    

    输出结果:

    Type reflect.TypeOf(): int
    reflect.ValueOf(): 99
    Type Value.Type(): int
    basic type, Kind(): int
    value.Int(): 99
    value.Interface(): 99
    value.Interface().(int): 99
    

    其中Interface()定义如下,

    func (v Value) Interface() (i interface{})
    

    用interface{}的方式返回v中动态值。等价于:

    var i interface{} = (v's underlying value)
    

    是上面提到的函数ValueOf()的反操作。

    Int()是经过断言后输出的结果。

    value.Interface().(int)是我们自己断言后输出的结果。

  • 相关阅读:
    学习git之路--1
    No input file specified. phpStudy nginx报错解决方案
    nginx隐藏tp路由index.php
    tp5命令行
    生成器
    php 解密小程序获取unionid
    根据GUID获取实例
    用SQL将数字转换为中文数字
    TFS无法确定工作区解决方案
    利用SQL语句产生分组序号
  • 原文地址:https://www.cnblogs.com/lanyangsh/p/11129087.html
Copyright © 2011-2022 走看看