golang interface 类型变量当作某个具体类型使用
比如,我们定义了一个 struct
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
然后有一个函数为了通用性,函数返回值类型为 interface,但是某种情况我们知道这个函数是返回 person 类型的,我们就可以
person.(person).Name
来调用 person 类型里面的东西,因为 interface 类型直接调用会报错。
官网一个例子:
var x interface{} = 7 // x has dynamic type int and value 7
i := x.(int) // i has type int and value 7 type I interface { m() } func f(y I) {
s := y.(string) // illegal: string does not implement I (missing method m)
r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
…
}
golang interface 类型变量当作某个具体类型使用的更多相关文章
- golang interface 类型学习
接口类型变量的内存结构 动态类型 动态值 对于动态类型指的是当其他非接口类型变量赋值给接口类型变量时,接口类型变量中的动态类型就是当前非接口类型 对于动态值指的就是当其他非接口类型变量赋值给接口类型变 ...
- golang interface
接口定义 Interface类型可以定义一组方法,但是这些不需要实现.并且interface不能 包含任何变量. type Interface interface { test1(a, b int) ...
- golang interface判断为空nil
要判断interface 空的问题,首先看下其底层实现. interface 底层结构 根据 interface 是否包含有 method,底层实现上用两种 struct 来表示:iface 和 ef ...
- 浅析 golang interface 实现原理
interface 在 golang 中是一个非常重要的特性.它相对于其它语言有很多优势: duck typing.大多数的静态语言需要显示的声明类型的继承关系.而 golang 通过 interfa ...
- Golang Interface 解析
转自 https://zhuanlan.zhihu.com/p/27652856 先看一段代码: 123456789101112 func (x interface{}) { if x == nil ...
- golang interface 多态
原文链接:http://www.52bd.net/code/210.html demo: package main import ( "fmt" ) //通知行为的接口 type ...
- shell编程系列4--有类型变量:字符串、只读类型、整数、数组
shell编程系列4--有类型变量:字符串.只读类型.整数.数组 有类型变量总结: declare命令和typeset命令两者等价 declare.typeset命令都是用来定义变量类型的 decla ...
- golang:interface{}类型测试
在golang中空的interface即interface{}可以看作任意类型, 即C中的void *. 对interface{}进行类型测试有2种语法: 1. Comma-ok断言: value, ...
- 工作随笔——Golang interface 转换成其他类型
新的公司,新的氛围.一年了,打算写点什么.so,那就写google的golang语言吧. 最最最基础的语法结构见go语言菜鸟教程 接下来写点菜鸟教程没有的. go语言的设计者认为:go语言必须让程序员 ...
随机推荐
- python3去除字符串中括号及括号里面的内容
a = """ <option value="search-alias=arts-crafts-intl-ship">Arts & ...
- 最详细的springmvc-mybatis教程
链接:http://blog.csdn.net/qq598535550/article/details/51703190
- 【Alpha】阶段第九次Scrum Meeting
[Alpha]阶段第九次Scrum Meeting 工作情况 团队成员 今日已完成任务 明日待完成任务 刘峻辰 编写获得所有学院接口 登出接口 赵智源 编写alpha版后测试点测试用例 编写脚本实现测 ...
- C# 打包
开发环境:VS2010+SQL Server 2008 操作系统:win7_32bit 旗舰版 开发语言:C# 项目名称:学生寄宿管理系统 下面开始介绍:如何给windows应用程序打包? 第一步: ...
- php----函数大全
字符串函数 数组函数 数学函数
- Oracle中创建自增字段方法
oracle没有ORACLE自增字段这样的功能,但是通过触发器(trigger)和序列(sequence)可以实现. 下面给大家讲个例子: 1.在Oracle中创建一个表: .创建一个表 ) prim ...
- 2D变换
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 蜗牛慢慢爬 LeetCode 19. Remove Nth Node From End of List [Difficulty: Medium]
题目 Given a linked list, remove the nth node from the end of list and return its head. For example, G ...
- PHP 多进程开发
pcntl_fork(); https://blog.csdn.net/wujiangwei567/article/details/77006724 https://blog.csdn.net/qq_ ...
- Oracle中SYS_CONNECT_BY_PATH函数的妙用 ;
Oracle 中SYS_CONNECT_BY_PATH函数是非常重要的函数,下面就为您介绍一个使用SYS_CONNECT_BY_PATH函数的例子,实例如下: 数据准备: ),b )); ', 'A' ...