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)是我们自己断言后输出的结果。

原文地址:https://www.cnblogs.com/lanyangsh/p/11129087.html