_嵌入类型_就是一个类型在另一个类型里面。下来看看Java是怎么实现的。
public class User {
String name;
String email;
public User(String name, String email){
this.name = name;
this.email = email;
}
}
先定义一个User类,参数是name和email,在定义一个Admin类,将User嵌入到Admin中。
public class Admin {
User user;
String level;
public Admin(User user, String level) {
this.user = user;
this.level = level;
}
}
定义一个Notifier接口,并写一个实现类。
public interface Notifier {
public void notifyForJava(User user);
}
实现类
public class UserImplementNotifier implements Notifier {
@Override
public void notifyForJava(User user) {
System.out.println("Sending User Email To " + user.name+ "<" + user.email + ">\n");
}
public static void main(String[] args) {
Admin admin = new Admin(new User("Bill", "bill@email.com"), "super");
Notifier userImplementNotifier = new UserImplementNotifier();
userImplementNotifier.notifyForJava(admin.user);
}
}
编写一个UserImplementNotifier类实现Notifier接口及相应notifyForJava方法,在main方法中new了一个Admin,传值给User和level,调用notifyForJava方法参数时User,使用admin.user传参。
在来看看Golang是怎么实现的。
import (
"fmt"
)
type notifier interface {
notify()
}
type user struct {
name string
email string
}
func (u *user) notify() {
fmt.Printf("Sending user email to %s<%s>\n",
u.name,
u.email)
}
type admin struct {
user
level string
}
func main() {
// Create an admin user.
ad := admin{
user: user{
name: "john smith",
email: "john@yahoo.com",
},
level: "super",
}
sendNotification(&ad)
}
func sendNotification(n notifier) {
n.notify()
}
结果
Sending user email to john smithjohn@yahoo.com
实现意思给上面Java的逻辑是一样的,就是定一个notifier接口、user和admin类型,使用user实现notifier接口,(go里面的接口实现是在func和notify接口方法中间添加~(u *user) ~ ),主要注意的是sendNotification(&ad)
,实现方法是sendNotification(n notifier)
为什么admin指针进行传参呢?不应该传的是user的指针&ad.user
么?这是由于Go中有内部类型提升的概念,Go发现admin类型没有实现这个接口,内部类型实现的这个接口会自动提升到外部类型,这以为着由于内部类型的实现,外部类型也同样实现了这个接口。
import (
"fmt"
)
type notifier interface {
notify()
}
type user struct {
name string
email string
}
func (u *user) notify() {
fmt.Printf("Sending user email to %s<%s>\n",
u.name,
u.email)
}
type admin struct {
user
level string
}
func (a *admin) notify() {
fmt.Printf("Sending admin email to %s<%s>\n",
a.name,
a.email)
}
func main() {
// Create an admin user.
ad := admin{
user: user{
name: "john smith",
email: "john@yahoo.com",
},
level: "super",
}
sendNotification(&ad)
ad.user.notify()
ad.notify()
}
func sendNotification(n notifier) {
n.notify()
}
结果
Sending admin email to john smithjohn@yahoo.com
Sending user email to john smithjohn@yahoo.com
Sending admin email to john smithjohn@yahoo.com
可见如果外部类型实现了接口,结果就是外部类型的,如果外部类型没有实现,内部类型实现,外部类型将自动实现。
总结,跟Java一样Go中也可以类型嵌套,实现编程灵活性和扩展性,但是Java中没有内部类型提升的概念,只能一层一层的引用。
参考:Go In Action