文章目录
- var a interface{} = “hello” str, ok := a.(string) if ok { fmt.Println(“转换成功:”, str) } else { fmt.Println(“转换失败”) }
- var a interface{} = 3.14 switch v := a.(type) { case int: fmt.Println(“是 int:”, v) case float64: fmt.Println(“是 float64:”, v) case string: fmt.Println(“是 string:”, v) default: fmt.Println(“未知类型”) }
目录
- 一、什么是 interface{}?
- 定义形式:
- 二、interface{} 有什么特别的?
- ✅ 特点:
- 三、使用示例
- 1. 存储任意类型的值:
- 四、底层原理:interface{} 是怎么存值的?
- 五、怎么取出 interface{} 中的值?
- 1. 类型断言(Type Assertion):
- 2. 使用类型分支(Type Switch):
- 六、常见使用场景
- 七、注意事项
- 八、面试常考问答
- 九、总结一句话:
在 Go 语言中,interface{} 是一种空接口(empty interface),它表示任意类型。因为它没有定义任何方法,所以 所有类型都实现了它。
interface{}
等价于:
type interface{} interface {}
-
所有类型都实现了 interface{}。
-
可以用来存储任意类型的值。
-
是 Go 的万能类型容器,类似于其他语言里的 Object 或 any。
所有类型都实现了 interface{}。
可以用来存储任意类型的值。
是 Go 的万能类型容器,类似于其他语言里的 Object 或 any。
func printAnything(v interface{}) {
fmt.Println("值是:", v)
}
func main() {
printAnything(123)
printAnything("hello")
printAnything([]int{1, 2, 3})
}
输出:
值是:123
值是:hello
值是:[1 2 3]
Go 编译器将 interface{} 实际存储为两部分:
type eface struct {
_type *_type // 真实类型信息
data unsafe.Pointer // 指向实际数据的指针
}
比如:
var a interface{} = 123
这时候:
-
_type:指向int的类型描述符; -
data:指向 123 这个 int 的值。
var a interface{} = "hello"
str, ok := a.(string)
if ok {
fmt.Println("转换成功:", str)
} else {
fmt.Println("转换失败")
}
var a interface{} = 3.14
switch v := a.(type) {
case int:
fmt.Println("是 int:", v)
case float64:
fmt.Println("是 float64:", v)
case string:
fmt.Println("是 string:", v)
default:
fmt.Println("未知类型")
}
| 场景 | 描述 |
|---|---|
| JSON 解析 | map[string]interface{} 可以存储任意结构 |
| fmt.Println | 接收的是 ...interface{} 参数 |
| 任意类型传参 | 写通用工具函数,允许接收任意类型 |
| 空值或未知类型变量 | 当不知道变量类型时,先存为 interface{} |
-
interface{} 存进去什么类型,取出来的时候必须断言正确,否则运行时报错。
-
interface{} 本身不能直接做加减乘除等运算,必须先类型断言。
-
不等于 JavaScript 的 any,Go 仍然是强类型语言,类型断言很重要。
-
interface{} 不能直接比较,除非内部类型支持 ==。
interface{} 存进去什么类型,取出来的时候必须断言正确,否则运行时报错。
interface{} 本身不能直接做加减乘除等运算,必须先类型断言。
不等于 JavaScript 的 any,Go 仍然是强类型语言,类型断言很重要。
interface{} 不能直接比较,除非内部类型支持 ==。
Q:interface{} 是不是万能的?
Q:interface{} 是不是万能的?
A:它可以存储任何类型的值,但你不能随便操作这些值,除非你知道它的真实类型,并且使用类型断言来还原它。
Q:interface{} 和 interface 的区别?
A:interface{} 是一种接口类型,没有定义任何方法;而普通的接口比如 Writer interface { Write(p []byte) (n int, err error) } 定义了方法,只有实现这些方法的类型才能赋值给该接口。
interface{} 是 Go 中可以表示任意类型的“空接口”,是实现泛型编程的基础工具之一。
到此这篇关于Golang interface{}的具体使用的文章就介绍到这了,更多相关Golang interface{}内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- golang interface{}类型转换的实现示例
- Golang-如何判断一个 interface{} 的值是否为 nil
- 详解Golang中interface{}的注意事项
- 深入了解Golang interface{}的底层原理实现
- Golang中interface{}转为数组的操作
- 解决golang 反射interface{}做零值判断的一个重大坑
- golang 实现interface{}转其他类型操作