类型限定
类型限定
现在我们回到类型{:?}
打印。因此,现在您可以看到如果要打印
fn print_number<T>(number: T) {
println!("Here is your number: {:?}", number); // ⚠️
}
fn main() {
print_number(5);
}
#[derive(Debug)]
。编译器也不知道,因此会出现错误:
error[E0277]: `T` doesn't implement `std::fmt::Debug`
--> src\main.rs:29:43
|
29 | println!("Here is your number: {:?}", number);
| ^^^^^^ `T` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
use std::fmt::Debug; // Debug is located at std::fmt::Debug. So now we can just write 'Debug'.
fn print_number<T: Debug>(number: T) { // <T: Debug> is the important part
println!("Here is your number: {:?}", number);
}
fn main() {
print_number(5);
}
因此,现在编译器知道#[derive(Debug)]
对其进行调试,因此现在我们也可以打印它。我们的函数可以使用
use std::fmt::Debug;
#[derive(Debug)]
struct Animal {
name: String,
age: u8,
}
fn print_item<T: Debug>(item: T) {
println!("Here is your item: {:?}", item);
}
fn main() {
let charlie = Animal {
name: "Charlie".to_string(),
age: 1,
};
let number = 55;
print_item(charlie);
print_item(number);
}
Here is your item: Animal { name: "Charlie", age: 1 }
Here is your item: 55
有时我们在通用函数中需要多个类型。我们必须写出每个类型名称,然后考虑我们要如何使用它。在此示例中,我们需要两种类型。首先,我们要打印类型为
use std::fmt::Display;
use std::cmp::PartialOrd;
fn compare_and_display<T: Display, U: Display + PartialOrd>(statement: T, num_1: U, num_2: U) {
println!("{}! Is {} greater than {}? {}", statement, num_1, num_2, num_1 > num_2);
}
fn main() {
compare_and_display("Listen up!", 9, 8);
}
- 首个类型为泛型
T ,它必须能够可以用于print 中被打印出来; - 第二个类型为泛型
U ,它必须能够可以用于print 中被打印出来,并且它能够进行比较。
需要注意的是啊,类型
use std::fmt::Display;
fn say_two<T: Display, U: Display>(statement_1: T, statement_2: U) { // Type T needs Display, type U needs Display
println!("I have two things to say: {} and {}", statement_1, statement_2);
}
fn main() {
say_two("Hello there!", String::from("I hate sand.")); // Type T is a &str, but type U is a String.
say_two(String::from("Where is Padme?"), String::from("Is she all right?")); // Both types are String.
}
I have two things to say: Hello there! and I hate sand.
I have two things to say: Where is Padme? and Is she all right?
where
为了使泛型函数更易于阅读,我们还可以在代码块之前的位置将其编写为:
use std::cmp::PartialOrd;
use std::fmt::Display;
fn compare_and_display<T, U>(statement: T, num_1: U, num_2: U)
where
T: Display,
U: Display + PartialOrd,
{
println!("{}! Is {} greater than {}? {}", statement, num_1, num_2, num_1 > num_2);
}
fn main() {
compare_and_display("Listen up!", 9, 8);
}
当您有许多泛型类型时,使用