[英]How to initialize a generic variable in Rust
在T
上的 function 泛型中,如何在安全(或不安全)Rust 中正确创建和初始化T
类型的变量? T
可以是任何东西。 做这种事情的惯用方式是什么?
fn f<T>() {
let t: T = todo!("what to put here?");
}
一种可能的用例可能是将T
用作交换的临时变量。
在T
上设置Default
绑定是在泛型 function 中构造泛型类型的惯用方式。
不过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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.