rust用struct保存特定trait的引用
2015-08-31 12:37
381 查看
结构体保存一个实现了某个trait的引用,只要是保存引用就必须显式的加lifetime,实现如下:
注意是实现了某个trait的类型的引用,而不是trait object
(只是保存而已,记不住…)
Play地址:http://is.gd/lIOAA6
输出结果:
这个列子可以实现把部分功能放在derive里,derive只需要实现这些trait就可以把自己的引用传递给base,这个比较方便库的封装,库保留一个接口给user,user实现了接口就可以实现回调
注意是实现了某个trait的类型的引用,而不是trait object
(只是保存而已,记不住…)
trait DeriveTrait{ fn hello(&self)->i32; } struct Base<'a,T:DeriveTrait+'a>{ pt:&'a mut T, } impl<'a,T:DeriveTrait> Base<'a,T> { fn new(t:&'a mut T)->Base<T>{ Base{ pt:t } } fn print(&self){ println!("hello from derive:{}",self.pt.hello()); } } struct Foo; impl DeriveTrait for Foo{ fn hello(&self)->i32{ 100 } } fn main(){ let mut f = Foo; let b = Base::new(&mut f); b.print(); }
Play地址:http://is.gd/lIOAA6
输出结果:
hello from derive:100
这个列子可以实现把部分功能放在derive里,derive只需要实现这些trait就可以把自己的引用传递给base,这个比较方便库的封装,库保留一个接口给user,user实现了接口就可以实现回调
相关文章推荐
- 不同RAID模式的优缺点
- win7旗舰版卸载“获取Windows10”升级助手
- leetcode 172 Factorial Trailing Zeroes(难易度:Easy)
- 详解C语言中的wait()函数和waitpid()函数
- 【LeetCode】70. Climbing Stairs
- [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use)错误原因
- Linux线程-互斥锁pthread_mutex_t http://blog.csdn.net/zmxiangde_88/article/details/7998458
- 减少页面回流与重绘(Reflow & Repaint)
- foxmail邮箱 邮件地址信息 以及邮件内容信息的导入导出
- XML 元素 http://blog.csdn.net/chaiyu2002/article/details/5967186
- xml节点和元素的关系 http://blog.csdn.net/chaiyu2002/article/details/5967186
- foxmail邮件太多,需要经常手工清理邮件怎么办
- UVALive - 2197 Paint the Roads(费用流)
- epoll详细工作原理 http://blog.csdn.net/hdutigerkin/article/details/7517390
- xmlInitParser和xmlCleanupParser使用详解 http://blog.csdn.net/hdutigerkin/article/details/7548596
- libxml读取xml文件的其他方法 http://blog.csdn.net/hdutigerkin/article/details/7547014
- libxml的使用(4)--xpath搜索节点树 http://blog.csdn.net/hdutigerkin/article/details/7546912
- libxml的使用(2)--读取节点属性 http://blog.csdn.net/hdutigerkin/article/details/7546907
- libxml的使用(1)--读取xml http://blog.csdn.net/hdutigerkin/article/details/7546899
- Leetcode #217 Contains Duplicate