Go_空接口

什么是空接口(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!  
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江小年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值