Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang interface{}

Golang interface{}的具体使用

作者:gopher.guo

interface{}是Go中可以表示任意类型的空接口,本文主要介绍了Golang interface{}的具体使用,具有一定的参考价值,感兴趣的可以了解一下

一、什么是 interface{}?

在 Go 语言中,interface{} 是一种空接口(empty interface),它表示任意类型。因为它没有定义任何方法,所以 所有类型都实现了它

定义形式:

interface{}

等价于:

type interface{} interface {}

二、interface{} 有什么特别的?

✅ 特点:

三、使用示例

1. 存储任意类型的值:

func printAnything(v interface{}) {
    fmt.Println("值是:", v)
}
​
func main() {
    printAnything(123)
    printAnything("hello")
    printAnything([]int{1, 2, 3})
}

输出:

值是:123
值是:hello
值是:[1 2 3]

四、底层原理:interface{} 是怎么存值的?

Go 编译器将 interface{} 实际存储为两部分:

type eface struct {
    _type *_type      // 真实类型信息
    data  unsafe.Pointer  // 指向实际数据的指针
}

比如:

var a interface{} = 123

这时候:

五、怎么取出 interface{} 中的值?

1. 类型断言(Type Assertion):

var a interface{} = "hello"
​
str, ok := a.(string)
if ok {
    fmt.Println("转换成功:", str)
} else {
    fmt.Println("转换失败")
}

2. 使用类型分支(Type Switch):

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{}

七、注意事项 

八、面试常考问答 

Q:interface{} 是不是万能的?

A:它可以存储任何类型的值,但你不能随便操作这些值,除非你知道它的真实类型,并且使用类型断言来还原它。

Q:interface{} 和 interface 的区别?

A:interface{} 是一种接口类型,没有定义任何方法;而普通的接口比如 Writer interface { Write(p []byte) (n int, err error) } 定义了方法,只有实现这些方法的类型才能赋值给该接口。

九、总结一句话:

interface{} 是 Go 中可以表示任意类型的“空接口”,是实现泛型编程的基础工具之一。

到此这篇关于Golang interface{}的具体使用的文章就介绍到这了,更多相关Golang interface{}内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文