簡體   English   中英

如何在 Rust 中初始化泛型變量

[英]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 並在泛型函數中使用它。

此外,如果一個類型實現了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)
}

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM