簡體   English   中英

如何命名Rust中關聯的function的類型?

[英]How to name the type of an associated function in Rust?

我正在嘗試編寫對操作通用的代碼,但也具有常用功能的便利功能,例如加法,我想為所有類型定義T: Add

如果我定義獨立函數,這很好用,因為我可以在返回值中使用impl Trait來隱藏不透明類型。

但是,如果我想在特征中定義這個 function ,我不得不將<T as Add>::add 我怎樣才能做到這一點?

use std::ops::Add;

struct Operation<T, F>
where
    F: Fn(T, T) -> T,
{
    arg: T,
    f: F,
}

fn addition<T>(arg: T) -> Operation<T, impl Fn(T, T) -> T>
where
    T: Add<Output = T>,
{
    Operation { arg, f: T::add }
}

trait Addable<T>
where
    T: Add<Output = T>,
{
    fn addition(self) -> Operation<T, impl Fn(T, T) -> T>;
    //fn addition(self) -> Operation<T, ???>;
}

錯誤:

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
  --> src/main.rs:22:39
   |
22 |     fn addition(self) -> Operation<T, impl Fn(T, T) -> T>;
   |                                       ^^^^^^^^^^^^^^^^^^

特征方法的返回值 position 中不允許使用impl Trait的原因是因為該方法可以有多個實現,而impl Trait僅在 function 或方法只有一個實現時才有效。

一種選擇是使用盒裝特征 object 閉包:

trait Addable<T>
where
    T: Add<Output = T>,
{
    fn addition(self) -> Operation<T, Box<dyn Fn(T, T) -> T>>;
}

但是,由於閉包似乎不太可能需要從其環境中捕獲變量,因此您可以改用普通的 function 指針。 這為您節省了不必要的堆分配。 這是一個簡單的i32示例,在 trait 方法返回類型中使用了一個普通的 function 指針:

trait Addable<T>
where
    T: Add<Output = T>,
{
    fn addition(self) -> Operation<T, fn(T, T) -> T>;
}

struct SomeType {
    arg: i32,
}

impl Addable<i32> for SomeType {
    fn addition(self) -> Operation<i32, fn(i32, i32) -> i32> {
        Operation {
            arg: self.arg,
            f: i32::add,
        }
    }
}

這是一個在特征方法返回類型中使用普通指針 function 的通用示例:

trait Addable<T>
where
    T: Add<Output = T>,
{
    fn addition(self) -> Operation<T, fn(T, T) -> T>;
}

struct SomeType<T> {
    arg: T,
}

impl<T> Addable<T> for SomeType<T>
    where T: Add + Add<Output = T>
{
    fn addition(self) -> Operation<T, fn(T, T) -> T> {
        Operation {
            arg: self.arg,
            f: T::add,
        }
    }
}

暫無
暫無

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

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