首页 > 解决方案 > 如何在 Rust 中初始化一个泛型变量

问题描述

在泛型函数中T,如何正确创建和初始化T安全(或不安全)Rust 类型的变量?T可以是任何东西。做这种事情的惯用方式是什么?

fn f<T>() {
    let t: T = todo!("what to put here?");
}

一种可能的用例可能是T用作交换的临时变量。

标签: genericsrustinitializationpolymorphismparametric-polymorphism

解决方案


设置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)
}

操场


推荐阅读