空接口与通用接口有何不同? [英] How is the empty interface different than a generic?

查看:96
本文介绍了空接口与通用接口有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我不完全了解泛型的功能,但是空接口interface{}与泛型有什么不同,特别是如果我们能够使用反射或类型开关的话?人们总是提到Go没有泛型,但是interface{}似乎可以像Java中的<T>一样完成这项工作.

Maybe I'm not fully versed on the power of generics, but how is the empty interface, interface{}, different than a generic, especially if we have the ability to use reflection or type switches? People always mention that Go doesn't have generics, but interface{} seems like it does the job pretty comparable to something like <T> in Java.

推荐答案

如果您来自Java,则空接口(interface{})实际上比使用泛型更接近使用Java中的Object变量.

If you come from Java, the empty interface (interface{}) is actually closer to working with Object variables in Java than with generics.

您可以为interface{}分配任何内容(就像在Java中使用Object变量一样).

You can assign anything to an interface{} (like you can do with an Object variable in Java).

但是,如果要使用存储在其中的实际类型,则应强制转换"或声明类型"(与Java中的Object变量相同).

But you should then "cast" or "type assert" back if you want to use the actual type you stored there (same that you need to do with Object variables in Java).

Java中的泛型完全不同,因为它们使您可以在编译时进行类型检查.唯一不同的是,如果您使用泛型,则无需求助于反射或类型切换.

Generics in Java are quite different, since they allow you to keep type checking at compile time. The different is precisely that you don't need to resort to reflection or type switches if you work with Generics.

您可以在此处阅读有关Java泛型的更多信息:

You can read more about Java generics here:

https://docs.oracle.com/javase/tutorial/java/generics /

然后按照此处和开始"游览的接下来的2或3步操作,详细了解空界面的工作原理:

And then follow this and the next 2 or 3 steps of the Go tour here for more on how the empty interface works:

https://tour.golang.org/methods/14

这篇关于空接口与通用接口有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆