【问题标题】:How to initialize a generic variable in Rust如何在 Rust 中初始化一个泛型变量
【发布时间】:2021-02-07 18:32:18
【问题描述】:

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

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

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

【问题讨论】:

  • 如果不是Default,你希望它初始化成什么?
  • 您已经回答了自己的问题。如果您不想使用不安全的代码,那么您必须在T 上放置一个Default 绑定并使用T::default() 初始化泛型类型。如果你愿意使用不安全的代码,那么你可以在 Rust 标准库中查找 rotate_right 的实现,或者直接使用 rotate_right
  • 您基本上是在问“除了标准库和语言允许我做 X 的方式之外,我该如何做 X?”
  • 我投票决定关闭,因为先发制人地排除了你知道的答案,你没有让我们知道什么样的答案是可以接受的。 rotate_right 在标准库中,您可以阅读它的代码——它只使用 unsafe(尽管不可否认,与您所指的方式不完全一样)。是什么让您认为需要另一种方式?或者为什么您排除的两个选项不能满足您的要求?
  • 我的意思不是你应该使用rotate_right,而是这个问题已经包含了两个合理的答案,并且似乎在问“还有什么?”解决方案没有任何实际参数。由于编辑问题不再有这个问题;我已经撤销了我的近距离投票。

标签: generics rust initialization polymorphism parametric-polymorphism


【解决方案1】:

Default 绑定到T 是在泛型函数中构造泛型类型的惯用方式。

Default 特征没有什么特别之处,您可以声明一个类似的特征并在您的泛型函数中使用它。

此外,如果一个类型实现了CopyClone,您可以从一个值初始化任意数量的副本和克隆。

注释示例:

// 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)
}

playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2020-03-15
    • 1970-01-01
    • 2014-04-13
    • 2019-03-16
    相关资源
    最近更新 更多