Basically, I want to implement pipeline-operator (binary operator for function application) on Box<T>
using Operator overloading in Rust.
I understand Box<T>
is a structure
https://doc.rust-lang.org/src/alloc/boxed.rs.html#175-178
and the below is the code I found here for struct Wrapped<T>(T)
that has the pipeline-operator as Shr >>
.
https://stackoverflow.com/a/17111630
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`
Here I want Box<T>
instead of Wrapped<T>
for the pipeline-operator.
I also found a code here to overload Add::add
for Vector
https://stackoverflow.com/a/28005283
impl<'a, 'b> Add<&'b Vector> for &'a Vector {
type Output = Vector;
fn add(self, other: &'b Vector) -> Vector {
Vector {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
Therefore, I suppose there must be a way to implement pipeline-operator (binary operator for function application) on Box<T>
.
So far, I did
use std::ops::Shr;
impl<A, B, F> Shr<F> for Box<A>
where
F: FnOnce(A) -> B,
{
type Output = Box<B>;
fn shr(self, f: F) -> Box<B> {
Box::new(f(&self))
}
}
etc. but the code doesn't work.
error[E0210]: type parameter `A` must be used as the type parameter for some local type (e.g., `MyStruct<A>`)
--> src/main.rs:6:10
|
6 | impl<A, B, F> Shr<F> for Box<A>
| ^ type parameter `A` must be used as the type parameter for some local type
|
= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
= note: only traits defined in the current crate can be implemented for a type parameter
Can you fix the code? Thanks.