什么是空接口(interface{}
)
- 它在Go语言中是一个特殊的接口,不包含任何方法声明
- 因此,任何类型都可以实现这个接口,因为不需要满足任何特定的方法要求,这使得空接口可以存储任意类型的值,提供了极大的灵活性
type i interface{}
var i interface{}
fmt.Printf("%T \n %v", i, i)
空接口的类型和值都是nil
空接口在程序中的作用
函数参数
package main
import "fmt"
func printValue(value interface{}) {
fmt.Println(value)
}
func main() {
printValue(42) // 输出: 42
printValue(3.14) // 输出: 3.14
printValue("Hello!") // 输出: Hello!
printValue(true) // 输出: true
printValue([]int{1, 2}) // 输出: [1 2]
}
package main
import "fmt"
func printValue(values interface{}) {
switch v := values.(type) {
case []int:
for _, value := range v {
fmt.Println(value)
}
default:
fmt.Println("Unsupported type")
}
}
func main() {
printValue(42)
printValue(3.14)
printValue("Hello!")
printValue(true)
printValue([]int{1, 2})
}
存储不同类型的值
package main
import "fmt"
func main() {
var values []interface{} // 切片,元素类型为空接口
values = append(values, 42)
values = append(values, 3.14)
values = append(values, "Hello!")
values = append(values, true)
for _, value := range values {
fmt.Println(value)
}
val := make([]interface{}, 5)
val[0] = 31
val[1] = "hello"
val[2] = []int{1, 2, 3, 4}
val[3] = "word"
for _, v := range val{
fmt.Println(v)
}
}
类型断言和类型切换
package main
import "fmt"
func inspectValue(value interface{}) {
switch v := value.(type) {
case int:
fmt.Printf("You've given an int: %d\n", v)
case string:
fmt.Printf("You've given a string: %s\n", v)
case bool:
fmt.Printf("You've given a bool: %t\n", v)
default:
fmt.Printf("Don't know the type!\n")
}
}
func main() {
inspectValue(42) // 输出: You've given an int: 42
inspectValue("Hello!") // 输出: You've given a string: Hello!
inspectValue(true) // 输出: You've given a bool: true
inspectValue(3.14) // 输出: Don't know the type!
}