gpt4 book ai didi

rust - 适用于Any的Rust管道运算符(通过重载运算符)

转载 作者:行者123 更新时间:2023-12-03 11:39:22 26 4
gpt4 key购买 nike

Composition operator and pipe forward operator in Rust

use std::ops::Shr;

struct Wrapped<T>(T);

impl<A, B, F> Shr<F> for Wrapped<A>
where
F: FnOnce(A) -> B,
{
type Output = Wrapped<B>;

fn shr(self, f: F) -> Wrapped<B> {
Wrapped(f(self.0))
}
}

fn main() {
let string = Wrapped(1) >> (|x| x + 1) >> (|x| 2 * x) >> (|x: i32| x.to_string());
println!("{}", string.0);
}
// prints `4`
这是用于struct的管道运算符的代码:通过重载运算符 Wrapped,但是我需要一个可用于 native 值(我认为是 &dyn Any)的代码。
由于我还不了解Rust的类型系统,所以我喜欢
use std::any::Any;

impl<A, B, F: Fn(A) -> B> Shr<F> for &dyn Any {
type Output = &dyn Any;

fn shr(self, f: F) -> &dyn Any {
f(self.0)
}
}
但是有明显的错误。
我该如何解决呢?谢谢。

最佳答案

感谢@mcarton,
Rust pipeline operator for Any by overloading operators
我找到了类似的解决方案:
https://docs.rs/apply/0.3.0/apply/trait.Apply.html

pub trait Apply<Res> {
/// Apply a function which takes the parameter by value.
fn apply<F: FnOnce(Self) -> Res>(self, f: F) -> Res
where
Self: Sized,
{
f(self)
}

/// Apply a function which takes the parameter by reference.
fn apply_ref<F: FnOnce(&Self) -> Res>(&self, f: F) -> Res {
f(self)
}

/// Apply a function which takes the parameter by mutable reference.
fn apply_mut<F: FnOnce(&mut Self) -> Res>(&mut self, f: F) -> Res {
f(self)
}
}

impl<T: ?Sized, Res> Apply<Res> for T {
// use default definitions...
}

fn main() {
let string = 1
.apply(|x| x * 2)
.apply(|x| x + 1)
.apply(|x: i32| x.to_string());
println!("{}", string);
}

关于rust - 适用于Any的Rust管道运算符(通过重载运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63767809/

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