Golang中接口和结构体之间转换的方法
在Golang中,接口和结构体之间的转换涉及到类型断言和类型断言的操作符。
接口转结构体
如果我们有一个接口变量,并且我们知道它的内部具体类型,我们可以使用类型断言来将其转换为该具体类型的结构体。
package main
import (
"fmt"
)
type MyInterface interface {
Show()
}
type MyStruct struct {
name string
}
func (m MyStruct) Show() {
fmt.Println(m.name)
}
func main() {
var a MyInterface
a = MyStruct{name: "John"}
b := a.(MyStruct)
b.Show()
}
结构体转接口
在Golang中,任何类型T的非空值都满足接口类型T,所以可以直接将结构体类型值赋值给接口类型变量。
package main
import (
"fmt"
)
type MyInterface interface {
Show()
}
type MyStruct struct {
name string
}
func (m MyStruct) Show() {
fmt.Println(m.name)
}
func main() {
var a MyInterface
a = MyStruct{name: "John"}
a.Show()
}
使用ok-idiom进行安全的类型断言
如果我们不确定接口变量的内部类型是否为我们想要的类型,我们可以使用ok-idiom来安全地执行类型断言。
package main
import (
"fmt"
)
type MyInterface interface {
Show()
}
type MyStruct struct {
name string
}
func (m MyStruct) Show() {
fmt.Println(m.name)
}
func main() {
var a MyInterface
a = MyStruct{name: "John"}
if b, ok := a.(MyStruct); ok {
b.Show()
} else {
fmt.Println("Not MyStruct type")
}
}
Do not communicate by sharing memory; instead, share memory by communicating.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)