簡體   English   中英

使用借位作為關聯的特征類型

[英]Using a borrow as an associated trait type

此代碼有效:

struct Test {
    val: String,
}

impl Test {
    fn mut_out(&mut self) -> &String {
        self.val = String::from("something");
        &self.val
    }
}

但是,更通用的實現不起作用:

struct Test {
    val: String,
}

trait MutateOut {
    type Out;
    fn mut_out(&mut self) -> Self::Out;
}

impl MutateOut for Test {
    type Out = &String;

    fn mut_out(&mut self) -> Self::Out {
        self.val = String::from("something");
        &self.val
    }
}

編譯器無法推斷字符串借用的生存期:

error[E0106]: missing lifetime specifier
  --> src/main.rs:13:16
   |
11 |     type Out = &String;
   |                ^ expected lifetime parameter

我無法找出一種明確聲明借用期限的方法,因為它取決於函數本身。

Deref特征中獲取靈感,您可以從關聯的類型中刪除引用,而只是在特征中注明要返回對關聯類型的引用:

trait MutateOut {
    type Out;
    fn mut_out(&mut self) -> &Self::Out;
}

impl MutateOut for Test {
    type Out = String;

    fn mut_out(&mut self) -> &Self::Out {
        self.val = String::from("something");
        &self.val
    }
}

是在操場上 假設您的函數名是mut_out ,那么如果要使用可變引用,那么這里也是一個操場示例

暫無
暫無

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

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