类型之间的 + 操作数是什么意思?
What does the + operand between types mean?
这个例子来自 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 的代数类型下找不到任何文档。
+
实际上在这里做什么,它叫什么?我在哪里可以找到这方面的文档?
T: <a href="https://doc.rust-lang.org/std/any/trait.Any.html" rel="nofollow noreferrer">Any</a> + <a href="https://doc.rust-lang.org/std/fmt/trait.Debug.html" rel="nofollow noreferrer">Debug</a>
is a trait bound. The type T
must satisfy Any
and Debug
, therefore the +
sign is used here and it is not related to algebraic types. You can read more on traits at the corresponding section in the book.
This section 提到 +
符号。
这个例子来自 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 的代数类型下找不到任何文档。
+
实际上在这里做什么,它叫什么?我在哪里可以找到这方面的文档?
T: <a href="https://doc.rust-lang.org/std/any/trait.Any.html" rel="nofollow noreferrer">Any</a> + <a href="https://doc.rust-lang.org/std/fmt/trait.Debug.html" rel="nofollow noreferrer">Debug</a>
is a trait bound. The type T
must satisfy Any
and Debug
, therefore the +
sign is used here and it is not related to algebraic types. You can read more on traits at the corresponding section in the book.
This section 提到 +
符号。