在T
的泛型函数中,我如何在安全(或不安全)Rust中正确创建和初始化类型为T
的变量?T
可以是任何东西。做这种事的习惯做法是什么?
fn f<T>() {
let t: T = todo!("what to put here?");
}
一个可能的用例是使用T
作为交换的临时变量。
将Default
绑定到T
上是在泛型函数中构造泛型类型的惯用方法。
Default
trait没有什么特别的,你可以声明一个类似的trait,并在你的泛型函数中使用它。
同样,如果一个类型实现了Copy
或Clone
,你可以从一个值初始化任意多的副本和克隆。
评论的例子:
// use Default bound to call default() on generic type
fn func_default<T: Default>() -> T {
T::default()
}
// note: there's nothing special about the Default trait
// you can implement your own trait identical to it
// and use it in the same way in generic functions
trait CustomTrait {
fn create() -> Self;
}
impl CustomTrait for String {
fn create() -> Self {
String::from("I'm a custom initialized String")
}
}
// use CustomTrait bound to call create() on generic type
fn custom_trait<T: CustomTrait>() -> T {
T::create()
}
// can multiply copyable types
fn copyable<T: Copy>(t: T) -> (T, T) {
(t, t)
}
// can also multiply cloneable types
fn cloneable<T: Clone>(t: T) -> (T, T) {
(t.clone(), t)
}
游乐场