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

最新文章

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

热门文章

  1. Linux Exploit系列之七 绕过 ASLR -- 第二部分
  2. SVM处理多分类问题
  3. docker 入门(2)
  4. postgres导入和导出
  5. Linux驱动开发之LED驱动
  6. linux pip使用国内源
  7. SimpleDateFormat问题
  8. jquery判断cookie是否存在
  9. vue cli3.0快速搭建项目详解(强烈推荐)
  10. maven生成jar包编码问题