翔云

Just try, don't shy. 最新文章请点击
随笔 - 294, 文章 - 0, 评论 - 27, 阅读 - 49万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

golang reflect 简单使用举例

Posted on   翔云123456  阅读(460)  评论(0编辑  收藏  举报

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

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示