当前位置:网站首页>golang 空接口
golang 空接口
2022-07-16 03:00:00 【@航空母舰】
空接口是接口类型的特殊形式。空接口没有任何方法,因此任何类型都无须实现空接口。从实现的角度来看,任何值都满足这个接口的需求。因此空接口类型可以保存任何值,也可以从空接口中取出原值。
- 空接口类型类似于 C# 或 Java 语言中的 Object、C语言中的 void*、C++ 中的 std::any。在泛型和模板出现前,空接口是一种非常灵活的数据抽象保存和使用的方法
- 空接口的内部实现保存了对象的类型和指针。使用空接口保存一个数据的过程会比直接用数据对应类型的变量保存稍慢。因此在开发中,应在需要的地方使用空接口,而不是在所有地方使用空接口。
空接口类型的变量可以存储任意类型的变量。
package main
import "fmt"
func main() {
// 定义一个空接口x
var x interface{}
s := "pprof.cn"
x = s
fmt.Printf("type:%T value:%v\n", x, x)
i := 100
x = i
fmt.Printf("type:%T value:%v\n", x, x)
b := true
x = b
fmt.Printf("type:%T value:%v\n", x, x)
}
空接口的应用
1.空接口作为函数的参数
使用空接口实现可以接收任意类型的函数参数。
// 空接口作为函数参数
func show(a interface{}) {
fmt.Printf("type:%T value:%v\n", a, a)
}
//函数的参数个数和每个参数的类型都不是固定的
func myfunc(args ...interface{}) {
}2.空接口作为map,数组,切片的各种类型的值
func main() {
// 空接口作为map值
var studentInfo = make(map[string]interface{})
studentInfo["name"] = "李白" //string
studentInfo["age"] = 18 //int
studentInfo["height"] = 1.82 //float
studentInfo["married"] = false //bool
fmt.Println(studentInfo)
var a = new([3]interface{})
a[0] = "Hello,World"
a[1] = 32
for _, b := range a {
fmt.Printf("%v\t%[1]T\n", b)
}
}3.类型断言
一个接口的值(简称接口值)是由一个具体类型和具体类型的值两部分组成的。这两部分分别称为接口的动态类型和动态值。
func main() {
var x interface{}
x = "pprof.cn"
v, ok := x.(string)
if ok {
fmt.Println(v)
} else {
fmt.Println("类型断言失败")
}
}上面的示例中如果要断言多次就需要写多个if判断,这个时候我们可以使用switch语句来实现:
func justifyType(any interface{}) {
switch v := any.(type) {
case string:
fmt.Printf("any is a string,value is: %v\n", v)
case int:
fmt.Printf("any is a int is: %v\n", v)
case bool:
fmt.Printf("any is a bool is: %v\n", v)
case float32:
fmt.Printf("any is a float32 is: %v\n", v)
default:
fmt.Printf("unsupport type:%T %v", v, v)
}
}
func main() {
var x interface{}
x = "pprof.cn"
justifyType(x)
x = 0.1
justifyType(x)
}因为空接口可以存储任意类型值的特点,所以空接口在Go语言中的使用十分广泛。
边栏推荐
- Error reporting solution - desktop and U disk data transmission error
- Where is the motivation to be a test / development programmer? How to persist
- How did the unsecured loan agreement on the chain perform in the encryption storm?
- 为什么 UDP 头只有 8 个字节
- ES6 browser support and running environment support detection and ES6 transcoding Es5
- 《通信软件开发与应用》结课报告
- 【性能测试】性能测试问答篇
- 3 minutes to understand the three waiting methods of Web Automation
- Programming old driver takes you to play with completable future asynchronous programming
- MySQL Basic - add and Advanced Query
猜你喜欢

MySQL foundation - add, delete, check and modify (Foundation)

Network security -- Kali uses mdk3 to attack WiFi (detailed tutorial)

缓存穿透、缓存雪崩、缓存击穿?

Indian Unicorn added another member: 5ire received a round a financing of US $100million at a valuation of US $1.5 billion

【Golang | gRPC】gRPC-Server Streaming服务端流实战

Etherscan: some important charts in the bear market

Radio and television 5g officially entered the arena: there is no four nation scuffle, but a two-line confrontation
![[today in history] July 15: Mozilla foundation was officially established; The first operation of Enigma cipher machine; Nintendo launches FC game console](/img/7d/7a01c8c6923077d6c201bf1ae02c8c.png)
[today in history] July 15: Mozilla foundation was officially established; The first operation of Enigma cipher machine; Nintendo launches FC game console

Programming old driver takes you to play with completable future asynchronous programming

做测试/开发程序员的动力来自哪里?怎样坚持下去呢......
随机推荐
Share the operation steps of postman connecting to MySQL database from the beginning of installation
QT writing IOT management platform 43 alarm SMS forwarding
Rust from and into
How did the unsecured loan agreement on the chain perform in the encryption storm?
Reversingkr WP (7)
I learned it slowly
Pytorch——报错解决:RuntimeError: Expected all tensors to be on the same device, but found at least two
Network security -- Kali uses mdk3 to attack WiFi (detailed tutorial)
软件测试—学习笔记3
《论文阅读》A Survey on Dialogue Systems: Recent Advances and New Frontiers
ReversingKr-wp(4)
Slave during MySQL master-slave configuration_ IO_ Running: connecting solution
【Golang | gRPC】使用TLS/SSL认证的gRPC服务
Use of zip/enumerate/map function
In depth analysis of multiple knapsack problem (Part 1)
3分钟弄懂web自动化的三种等待方式
动作捕捉协助中国电力科学研究院建立边云协同电力自主巡检系统
Yin Yang translation
Rust iter& match
Kotlin compose bottom bar