golang reflect 简单使用举例
2024-10-07 04:05:48
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)
是我们自己断言后输出的结果。
最新文章
- jmeter jar包
- spark的standlone模式安装和application 提交
- 编写高质量代码--改善python程序的建议(六)
- Linux内核简介
- Codeforces Round #209 (Div. 2)C
- Python装饰器(decorator)
- (转)集成架构:对比 Web API 与面向服务的架构和企业应用程序集成
- VMware ESXi CentOS Linux虚拟机安装VMware Tools教
- 【关于JavaScript】自动计算的实例
- 几个常用的CSS3样式代码以及不兼容的解决办法
- hdu_2328_Corporate Identity(暴力枚举子串+KMP)
- 现代3D图形编程学习-设置三角形颜色(译)
- 【Spring】DispatcherServlet源码分析
- mysqlQL 5.7 安装报错CMake Error at cmake/boost.cmake:81 (MESSAGE)
- [转] mongodb下载、安装、配置与使用
- ModelAttribue注解的使用
- android openCL的so库目录(转)
- [项目实施失败讨论Case] “凭心而论,在这家公司很敬业的工作了3年多,老板最后给我下的评语,大家都看看吧,千万别和我走同一条路!”(摘自csdn)
- pyhont备份php代码脚本
- ubuntu的安装方法