将结构指针转换为接口{}
时间:2023-04-14
浏览:127
作者:佚名
今天golang学习网给大家带来了《将结构指针转换为接口{}》,其中涉及到的知识点包括golang等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
问题内容
如果我有:
type foo struct{
}
func bar(baz interface{}) {
}
以上是一成不变的——我不能改变 foo 或 bar。此外,baz 必须转换回 bar 内的 foo 结构指针。如何将 &foo{} 转换为 interface{} 以便在调用 bar 时将其用作参数?
正确答案
变成*foo一个interface{}是微不足道的:
f := &foo{}
bar(f) // every type implements interface{}. Nothing special required
为了回到 a *foo,你可以做一个 类型断言 :
func bar(baz interface{}) {
f, ok := baz.(*foo)
if !ok {
// baz was not of type *foo. The assertion failed
}
// f is of type *foo
}
或 类型开关
(类似,但如果baz可以是多种类型则很有用):
func bar(baz interface{}) {
switch f := baz.(type) {
case *foo: // f is of type *foo
default: // f is some other type
}
}
好了,本文到此结束,带大家了解了《将结构指针转换为接口{}》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.26
11.26
热门专题
