【问题标题】:Can one alias higher rank trait bound in rust?一个别名更高等级的性状可以与生锈结合吗?
【发布时间】:2019-05-25 16:44:46
【问题描述】:

我的程序有一堆对通用整数进行操作的函数。它们通常具有以下形式:

use num::{FromPrimitive, Integer, ToPrimitive};
use std::cmp::Ord;
use std::ops::{Add, Mul};

fn function<'a, I>(n: &'a I) -> I
where
    I: Integer + Clone + FromPrimitive + ToPrimitive,
    for<'b> &'b I: Mul<Output = I> + Add<Output = I> + Ord,
{

}

我想给泛型类型要求起别名:

I: Integer + Clone + FromPrimitive + ToPrimitive,
for<'b> &'b I: Mul<Output = I> + Add<Output = I> + Ord,

这样我就不需要每次都重写它们。最初,我认为宏会有所帮助,但看起来它们不像在 C 中那样工作,所以我寻找了另一种方法。

我找到了一种方法来满足第一个要求。必须对任何类型 T 的已定义特征应用默认实现。

trait GInteger: Integer + Clone + FromPrimitive + ToPrimitive {}
impl<T: Integer + Clone + FromPrimitive + ToPrimitive> GInteger for T {}

那么我可以简单地写:

I: GInteger

而不是

I: Integer + Clone + FromPrimitive + ToPrimitive,

如何为第二个要求设置别名?有可能吗?

for<'b> &'b I: Mul<Output = I> + Add<Output = I> + Ord,

【问题讨论】:

    标签: rust


    【解决方案1】:

    不,不可能为此使用新特征。

    虽然可以将第二个要求包含在特征定义中...

    trait GInteger: Integer + Clone + FromPrimitive + ToPrimitive
    where
        for<'b> &'b Self: Mul<Output = Self> + Add<Output = Self> + Ord,
    {
    }
    

    rustc 不会为您详细说明where 子句,所以在function() 的声明中您仍然需要编写where for&lt;'b&gt; &amp;'b I: ... 绑定。这是一个known bug

    fn function<I: GInteger>(n: &I) -> I
    where
        for<'b> &'b I: Mul<Output = I> + Add<Output = I> + Ord,  // meh
    {
        n * n
    }
    

    如果你使用 nightly Rust,你可以改用trait alias (RFC 1733),这正好解决了这个问题。

    #![feature(trait_alias)]
    
    use num::{FromPrimitive, Integer, ToPrimitive};
    use std::cmp::Ord;
    use std::ops::{Add, Mul};
    
    // Define a trait alias
    trait GInteger = Integer + Clone + FromPrimitive + ToPrimitive
    where
        for<'b> &'b Self: Mul<Output = Self> + Add<Output = Self> + Ord;
    
    // Just use it
    fn function<I: GInteger>(n: &I) -> I {
        n * n
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2012-01-14
      • 1970-01-01
      相关资源
      最近更新 更多