作为函数返回值的特征 [英] Traits as a return value from a function

查看:40
本文介绍了作为函数返回值的特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个枚举,NormalColourBoldColour,它们都实现了 Colour 特性.它们包含 BlueBoldGreen 等.

I have two enums, NormalColour and BoldColour, both of which implement the Colour trait. They contain Blue, BoldGreen, and so on.

我想从同一个函数中返回这两种类型的值,将它们视为只是一个 Colour 值,调用 paint 函数结果,但我找不到强制 Rust 编译器为我做这件事的方法.我希望能够写出这样的东西:

I'd like to return values of both of these types from the same function, treating them as though they're just a Colour value, calling the paint function on the result, but I can't find a way to coerce the Rust complier into doing this for me. I'd like to be able to write something like this:

pub trait Colour {
    fn paint(&self, input: &str) -> String;
}

fn file_colour(stat: &io::FileStat) -> Colour {
    if stat.kind == io::TypeDirectory {
        Blue
    } else if stat.perm & io::UserExecute == io::UserExecute {
        BoldGreen
    } else {
        White
    }
}

我需要什么类型才能让函数返回才能工作?

What type do I have to make the function return for it to work?

我最终会让更多类型实现Colour,这就是为什么我对将两个枚举变成一个大枚举不感兴趣.

I'll eventually like to make more types implement Colour, which is why I'm not interested in just turning the two enums into one big enum.

推荐答案

答案是 trait 对象.这意味着您将使用 Box 作为您的类型;裸 Colour 不是可实例化的类型.您可以使用 as 运算符将 Box 对象转换为 Box:Box::new(NormalColour::白色)作为框<颜色>.在很多地方这是没有必要的(只需编写 Box::new(NormalColour::White) 并且它可以被自动强制转换为 Box),但有时它仍然是必要的.

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.

这篇关于作为函数返回值的特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆