Traits as a return value from a function [duplicate]

不想你离开。 提交于 2019-11-28 13:28:08

The answer is trait objects. This means that you will work with Box<Colour> as your type; bare Colour is not an instantiable type. You can cast Box<T> objects to Box<Colour> with the as operator: Box::new(NormalColour::White) as Box<Colour>. In many places this is not necessary (just write Box::new(NormalColour::White) and it can be automatically coerced to Box<Colour>), but sometimes it will still be necessary.

Still, if you can do it as an enum, that will probably be a nicer solution.

Sean Perry

The answer above suggests:

fn file_colour(stat: &io::FileStat) -> Box<Colour> { /* ... */ }

which works, but you need to wrap all of the returns in a Box::new() call.

However, in Rust 1.26 you can now say

fn file_colour(stat: &io::FileStat) -> impl Colour { /* ... */ }

and simply return the value. No Box needed.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!