generics - 如何在 Rust 中初始化一个泛型变量
问题描述
在泛型函数中T
,如何正确创建和初始化T
安全(或不安全)Rust 类型的变量?T
可以是任何东西。做这种事情的惯用方式是什么?
fn f<T>() {
let t: T = todo!("what to put here?");
}
一种可能的用例可能是T
用作交换的临时变量。
解决方案
设置Default
界限T
是在泛型函数中构造泛型类型的惯用方式。
不过,该特征没有什么特别之处Default
,您可以声明一个类似的特征并在您的通用函数中使用它。
此外,如果一个类型实现了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)
}
推荐阅读
- c++ - 如何正确地为字符串“数组”动态分配内存
- rest - “您的密码不符合要求”的 HTTP 状态代码
- powershell - 使用 Powershell 创建快捷方式未按预期工作
- android - 使用 Retrofit、Moshi 和 Kotlin 展开封装响应
- string - 如何以数学方式评估字符串?(例如“4*4+1/1”= 17)
- image-processing - 手势识别数据集
- r - R:在插入符号模型上使用 rms::fastbw 进行反向特征选择时出错
- c++ - 在 Eigen 中实现 Clip()
- unreal-engine4 - Oculus Quest:无法为 C++ 生成 VS 项目
- bash - `man` 不尊重 `MANPAGER` 除非它被显式调用