Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

golang接口的问题,某个类型要实现接口, 那类型方法的字面量要与接口声明的方法的字面量一模一样?

比如现在有产品接口(Product)和具体的产品A(ProductA):


// Product 产品接口
type Product interface {
    GetInfo() string
}

// ProductA 具体产品A, 实现了Product接口
type ProductA struct {
    name string
}

func (p *ProductA) GetInfo() string {
    return p.name
}

生产者接口(Creator)和具体生产者A(CreatorA):

// Creator 生产者接口
type Creator interface {
    Produce() Product   // 接口方法声明返回值是一个产品接口类型
 }
 
 // CreatorA 具体生产者A
 type CreatorA struct {}
 
 func (c *CreatorA) Produce() *ProductA {   // 这样写CreatorA就没实现接口Creator
    return &ProductA{"xxx"}
}

*ProductA是一个实现了接口Product的类型, 但是func(c *CreatorA) Product() *ProductA却不符合接口Creator?
只有写成func(c *CreatorA) Product() Product才符合了接口Creator, 那是不是就是说具体方法的声明要跟接口声明写的一毛一样才有效?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

当然要一样
接口就是一种基本的方法集、数据类型集,不涉及到具体的实现,可以看成是一种预定义。
而你的类型struct,类似我们说的对象,类型(对象)要实现接口,那么必须实现接口里边的方法,与接口里边的方法一致(包括方法的返回值类型一致)我们才能说实现了那个接口。

ProductA---》实现了 接口Product
其中CreatorA想要实现Creator接口,就得实现Creator接口里边的Produce方法;
这个方法必须返回Product接口;
换句话说,想要CreatorA实现Creator接口,在实现这个接口里边的Produce方法的时候,要保持与接口里边这个方法一致,返回值一致,也就是返回Prokuct接口才行

而你定义的这个Produce方法,返回的是ProductA(一个实现了Product接口的对象),不是Product接口,返回值类型不一样(虽然它底层实现了Product接口),也不能说实现了
必须是func(c *CreatorA) Produce() Product

由此可见,golang中接口与方法实现,要求还挺严格的,实现的接口方法返回值必须一致才行,光底层一致不行


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...