内容简介:interface接口还可以作为函数参数,因为interface的变量可以持有任意实现该interface类型的对象,我们可以通过定义interface参数,让函数接受各种类型的参数。 判断interface变量存储的元素的类型,目前常用的有两种方法:Comma-ok断言和switch测试。
interface接口还可以作为函数参数,因为interface的变量可以持有任意实现该interface类型的对象,我们可以通过定义interface参数,让函数接受各种类型的参数。 判断interface变量存储的元素的类型,目前常用的有两种方法:Comma-ok断言和switch测试。
/**
* interface接口作为函数参数
* 判断interface变量存储的元素的类型
*/
package main
import (
"fmt"
"strconv"
)
// 定义Human对象
type Human struct {
name string
age int
phone string
}
// 定义空接口
type Element interface{}
// 定义切片
type List []Element
// 定义Person对象
type Person struct {
name string
age int
}
// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Human对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Human对象可以作为fmt.Println的参数被调用
func (h Human) String() string {
return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">"
}
// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Person对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Person对象可以作为fmt.Println的参数被调用
func (p Person) String() string {
return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}
func main() {
// interface作为函数的参数传递
Lucy := Human{"Lucy", 29, "10086"}
fmt.Println("This human is:", Lucy)
list := make(List, 3)
list[0] = 100
list[1] = "Hello Golang!"
list[2] = Person{"Lily", 19}
// Comma-ok断言
for index, element := range list {
// 判断变量的类型 格式:value, ok = element(T)
// value是interface变量的值,ok是bool类型,element是interface的变量,T是断言的interface变量的类型
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is a different type\n", index)
}
}
// switch
for index, element := range list {
// 注意:element.(type)语法不能在switch外的任何逻辑中使用
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
default:
fmt.Printf("list[%d] is a differernt type", index)
}
}
}
以上所述就是小编给大家介绍的《Golang语言中的interface是什么(下)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 编译型语言、解释型语言、静态类型语言、动态类型语言概念与区别
- 计算机语言发展的三个阶段:机器语言、汇编语言与高级语言
- 凹 (“Wa”) 语言:可以嵌入 Go 语言环境的脚本语言
- Rust语言恰巧是一门解决了Go语言所有问题的语言
- 获取系统语言/当前 App支持语言
- 【Go 语言教程】Go 语言简介
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Sovereign Individual
James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00
Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!