golang 接口使用
TsingCall · · 5127 次点击 · · 开始浏览先说结论:
1、接口可以多层继承,只要最终的对象能实现接口的属性
2、实现接口的类型子孙层只能使用接口方法,不能使用子孙类型的属性
这两句话很绕,我们用一段代码说明下
代码orm_test.go如下:
package orm_test
import (
"fmt"
"reflect"
"testing"
)
type Father interface {
animals(animal string) string
plants(plant string) string
}
type son struct {
}
//实现接口方法
func (s *son) animals(animal string) string {
return animal
}
func (s *son) plants(plant string) string {
return plant
}
type sons1 struct {
Father
}
type sons2 struct {
Father
}
func (s1 *sons1) A(a string) {
fmt.Println(a)
}
func (s2 *sons2) B(b string) {
fmt.Println(b)
}
func TestOrm(t *testing.T) {
//son才是接口的真正实现
b := &sons1{
Father: &sons2{Father: &son{}},
}
c := &sons2{
Father: &son{},
}
//最终的方法都是调用son对象的方法
fmt.Println(b.animals("两层接口继承:animals"))
fmt.Println(c.plants("一层接口继承:plants"))
fmt.Println(reflect.TypeOf(b.Father)) //*orm_test.sons2
fmt.Println(reflect.TypeOf(c)) //*orm_test.sons2
fmt.Println(b.Father.plants("一层接口继承:plants"))
fmt.Println(b.Father.animals("一层接口继承:animals"))
c.B("c的B方法实现") //输出结果:c的B方法实现
//b.Father.B("Other") //undefined (type Father has no field or method B)
}
执行代码结果:
=== RUN TestOrm
两层接口继承:animals
一层接口继承:plants
*orm_test.sons2 #可以看到c和b.Father都属于sons2指针类型,但是b.Father并不能使用sons2方法,只能接口继承,因为它本身是一个接口
*orm_test.sons2
一层接口继承:plants
一层接口继承:animals
--- PASS: TestOrm (0.00s)
PASS
ok command-line-arguments 0.009s
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
先说结论:
1、接口可以多层继承,只要最终的对象能实现接口的属性
2、实现接口的类型子孙层只能使用接口方法,不能使用子孙类型的属性
这两句话很绕,我们用一段代码说明下
代码orm_test.go如下:
package orm_test
import (
"fmt"
"reflect"
"testing"
)
type Father interface {
animals(animal string) string
plants(plant string) string
}
type son struct {
}
//实现接口方法
func (s *son) animals(animal string) string {
return animal
}
func (s *son) plants(plant string) string {
return plant
}
type sons1 struct {
Father
}
type sons2 struct {
Father
}
func (s1 *sons1) A(a string) {
fmt.Println(a)
}
func (s2 *sons2) B(b string) {
fmt.Println(b)
}
func TestOrm(t *testing.T) {
//son才是接口的真正实现
b := &sons1{
Father: &sons2{Father: &son{}},
}
c := &sons2{
Father: &son{},
}
//最终的方法都是调用son对象的方法
fmt.Println(b.animals("两层接口继承:animals"))
fmt.Println(c.plants("一层接口继承:plants"))
fmt.Println(reflect.TypeOf(b.Father)) //*orm_test.sons2
fmt.Println(reflect.TypeOf(c)) //*orm_test.sons2
fmt.Println(b.Father.plants("一层接口继承:plants"))
fmt.Println(b.Father.animals("一层接口继承:animals"))
c.B("c的B方法实现") //输出结果:c的B方法实现
//b.Father.B("Other") //undefined (type Father has no field or method B)
}
执行代码结果:
=== RUN TestOrm
两层接口继承:animals
一层接口继承:plants
*orm_test.sons2 #可以看到c和b.Father都属于sons2指针类型,但是b.Father并不能使用sons2方法,只能接口继承,因为它本身是一个接口
*orm_test.sons2
一层接口继承:plants
一层接口继承:animals
--- PASS: TestOrm (0.00s)
PASS
ok command-line-arguments 0.009s