Macaron的注入interface

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

#上一篇 http://my.oschina.net/u/943306/blog/506905
上一篇介绍了Macaron里的注入Struct,这篇介绍注入interface
两者的区别在于:

  1. 使用方法不同,注入Struct用的是Map,而注入interface的是MapTo
  2. 注入Struct的话,只能用该类型的Struct,而注入interface的话,可以用任何实现interface的Struct

#先上代码

package mainimport ("fmt""github.com/Unknwon/macaron"
)func main() {m := macaron.Classic()m.Use(MidInterface("laoshi")) //底层使用了MapTo而不是Map了m.Get("/", func(ctx *macaron.Context, s STUDENT) { //这里要用接口的方式传入,而不能用*Student了fmt.Println(s.GetName())s.Job()  //上面用的是“laoshi”,所以打印的是teach...,改成“xuesheng”试试结果})m.Run()
}//新添加的,用于代替MidStruct
func MidInterface(opt string) macaron.Handler {var s STUDENTif opt == "laoshi" {s = &Teacher{Id: 1, Name: "xiao ming"}} else {s = &Student{Id: 1, Name: "xiao wang"}}return func(ctx *macaron.Context) {ctx.MapTo(s, (*STUDENT)(nil)) //MapTo用来注册interface}
}//MidStruct在这里没有用到,用于和MidInterface比较而保留在此
func MidStruct(opt string) macaron.Handler {var s *Studentif opt == "xm" {s = &Student{Id: 1, Name: "xiao ming"}} else {s = &Student{Id: 1, Name: "xiao wang"}}return func(ctx *macaron.Context) {ctx.Map(s)  //Map用来注册struct}
}//新加一个STUDENT的接口,下面的Student和Teacher都已经实现了该接口
type STUDENT interface {GetName() stringJob()
}type Student struct {Id   intName string
}func (s *Student) GetName() string {return s.Name
}func (s *Student) Job() {fmt.Println("study..")
}//新加一个Teacher的struct
type Teacher struct {Id   intName string
}func (t *Teacher) GetName() string {return t.Name
}func (t *Teacher) Job() {fmt.Println("teach...")
}

#代码分析

上一篇只有1个Struct,也就是Student
这里有2个Struct,一个是Student,另一个是Teacher。这两个Struct都实现了STUDENT这个interface

现在注入的时候用ctx.MapTo(s, (*STUDENT)(nil))这个方法,来注入。其中第一个参数s可以是Student,也可以是Teacher。第二个参数是一个接口哦,注意。

注册完成后,就可以用了,就是这句m.Get("/", func(ctx *macaron.Context, s STUDENT),注意的是,这里是STUDENT,还是接口。

当调用接口上的方法时,s.Job()会知道这个接口背后是哪个具体类型,如果是Student,就会打印study...,如果是Teacher就会打印teach...

转载于:https://my.oschina.net/u/943306/blog/506944


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部