关于 'static 的特征约束详细解释,请参见 Rust 语言圣经,这里就不再赘述。
5. 🌟🌟
/* 让 代 码 工 作 */
use std::fmt::Debug;
fn print_it<T: Debug + 'static>( input: T) {
println!( "'static value passed in is: {:?}", input );
}
fn print_it1( input: impl Debug + 'static ) {
println!( "'static value passed in is: {:?}", input );
}
fn print_it2<T: Debug + 'static>( input: &T) {
println!( "'static value passed in is: {:?}", input );
}
fn main() {
// i 是 有 所 有 权 的 数 据 , 并 没 有 包 含 任 何 引 用 , 因 此 它 是 'static
let i = 5;
print_it(i);
// 但 是 &i 是 一 个 引 用 , 生 命 周 期 受 限 于 作 用 域 , 因 此 它 不 是 'static
print_it(&i);
print_it1(&i);
// 但 是 下 面 的 代 码 可 以 正 常 运 行 !
print_it2(&i);
}
6. 🌟🌟🌟
use std::fmt::Display;
fn main() {
let mut string = "First".to_owned();
string.push_str(string.to_uppercase().as_str());
print_a(&string);
print_b(&string);
print_c(&string); // Compilation error
print_d(&string); // Compilation error
print_e(&string);
print_f(&string);
print_g(&string); // Compilation error
}
fn print_a<T: Display + 'static>(t: &T) {
println!("{}", t);
}
fn print_b<T>(t: &T)
where
T: Display + 'static,
{
println!("{}", t);
}
fn print_c(t: &'static dyn Display) {
println!("{}", t)
}
fn print_d(t: &'static impl Display) {
println!("{}", t)
}
fn print_e(t: &(dyn Display + 'static)) {
println!("{}", t)
}
fn print f(t: &(impl Display + 'static)) {
fn print_f(t: &(impl Display + static)) {
println!("{}", t)
}
fn print_g(t: &'static String) {
println!("{}", t);
}