gpt4 book ai didi

rust - 一个别名可以在 rust 中绑定(bind)更高等级的特征吗?

转载 作者:行者123 更新时间:2023-11-29 08:08:25 25 4
gpt4 key购买 nike

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

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,

最佳答案

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

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

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

rustc 不会详细说明 where子句,所以在 function() 的声明中你还需要写 where for<'b> &'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
}

关于rust - 一个别名可以在 rust 中绑定(bind)更高等级的特征吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56306834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com