type People interface {
say()
walk()
}
type Student struct {
id int
name string
}
//构造函数技巧:实例化结构体返回的不是结构体本身(Student),而是结构体想要实现的接口(People)
//这样子,如果结构体Student若没有实现接口People全部的方法,代码就会实现自检提示出错。
func NewStudent(id int, name string) People {
return &Student{id: id, name: name}
}
func (s *Student) say() {
fmt.Println(s.name + " say his id is :" + strconv.Itoa(s.id))
}
func (s *Student) walk() {
fmt.Println(s.name + " walk")
}
func Test83() {
student := NewStudent(10, "cowboy")
student.say()
student.walk()
}
还有另外一种面向接口编程的方式
type Weixin struct {
pay_type string
}
//⭐这个是关键,定义一个变量(不需要使用的,所以用下划线代替),类型是结构体Weixin要实现的接口Payment,赋值是结构体的空值。
//如果Weixin结构体没有完全实现接口,这里的赋值就会报错。实现了自动检测结构体是否实现接口。
var _ Payment = Weixin{}
type Payment interface {
Pay()
Refund()
}
func (w Weixin) Pay() {
fmt.Println(w.pay_type + "支付成功")
}
func (w Weixin) Refund() {
fmt.Println(w.pay_type + "退款成功")
}
func NewWeixin(pay_type string) *Weixin {
return &Weixin{pay_type: pay_type}
}
func PayWay() {
pay := NewWeixin("wx")
pay.Pay()
pay.Refund()
}