类型之间的+操作数是什么意思?

时间:2019-04-08 16:17:39

标签: rust algebraic-data-types static-typing

使用core::any

中的示例
use std::fmt::Debug;
use std::any::Any;

// Logger function for any type that implements Debug.
fn log<T: Any + Debug>(value: &T) {
    let value_any = value as &dyn Any;

    // try to convert our value to a String.  If successful, we want to
    // output the String's length as well as its value.  If not, it's a
    // different type: just print it out unadorned.
    match value_any.downcast_ref::<String>() {
        Some(as_string) => {
            println!("String ({}): {}", as_string.len(), as_string);
        }
        None => {
            println!("{:?}", value);
        }
    }
}

// This function wants to log its parameter out prior to doing work with it.
fn do_work<T: Any + Debug>(value: &T) {
    log(value);
    // ...do some other work
}

fn main() {
    let my_string = "Hello World".to_string();
    do_work(&my_string);

    let my_i8: i8 = 100;
    do_work(&my_i8);
}

这是我第一次看到类型+之间的 Any + Debug 操作数。我假设它像algebraic types,因此将是Any类型的Debug类型;但是,我在Rust中找不到任何代数类型的文档。

+在这里实际上是做什么的,它叫什么?在哪里可以找到相关文档?

1 个答案:

答案 0 :(得分:5)

T: Any + Debugtrait bound。类型T必须满足Any Debug,因此此处使用+符号,它与代数类型无关。您可以在corresponding section in the book上阅读有关特征的更多信息。

This section提到了+符号。