I'm interested in this program:
fn main() {
let mut y = 13;
let mut x = &y;
x = &*x;
println!("{}", x);
}
In this case, the statement x = &*x; is translated into the following MIR:
_4 = _2; // scope 2 at src/main.rs:4:9: 4:12
_3 = _4; // scope 2 at src/main.rs:4:9: 4:12
_2 = move _3; // scope 2 at src/main.rs:4:5: 4:12
Basically, x = &*x; is translated as x = x; (i.e. a NOP). If I change the program like so:
fn main() {
let mut i = 13;
let mut j = 13;
let mut y = &i;
let mut x = &j;
x = &*y;
println!("{}", x);
}
Then, again, x = &*y; is essentially translated as x = y;.
Now my question (finally): Is a reborrow &*y when y is an immutable borrow always equivalent to just reading y?
Of course, I understand that if y was a mutable borrow this would be an entirely different thing.
Related
My previous QA
What is the type for |x| move |y| x + y?
Thanks to the provided answer, the following code works.
#![feature(type_alias_impl_trait)]
type Adder = impl Fn(isize) -> isize;
type Plus = fn(isize) -> Adder;
let plus: Plus = |x| move |y| x + y;
println!("{}", plus(9)(1)); //10
Based on this, now I try to re-define map Functor.
#![feature(type_alias_impl_trait)]
type Mapper<A, B> = impl Fn(Vec<A>) -> Vec<B>;
type Map = <A, B>(fn(fn(A) -> B) -> Mapper<A, B>);
let map:Map = |f| move |A| A.map(f);
let f = |a| a * 2;
let A = vec![1, 2, 3];
let B = map(f)(A);
However, the first line got an error: could not find defining uses, the second line, for <A, B> syntax error.
Is it possible to fix this?
It looks like you want a generic function, so define one directly:
#![feature(type_alias_impl_trait)]
fn main() {
type Mapper<A, B> = impl Fn(Vec<A>) -> Vec<B>;
//type Map<A, B> = fn(fn(A) -> B) -> Mapper<A, B>;
//let map: Map::<A, B> = |f| move |a: Vec<A>| a.into_iter().map(f).collect();
fn map2<A, B>(f: fn(A) -> B) -> Mapper<A, B> {
move |a| a.into_iter().map(f).collect()
}
let f = |a| a * 2;
let a = vec![1, 2, 3];
//let b = map(f)(a);
let b = map2(f)(a);
// show result
println!("{:?}", b);
}
Check this.
let mut x = 1;
let a = &mut x;
let b = &mut *a;
*a = 2; // error. b borrows a
*b = 3; // it works! (only without " *a = 2 ")
let mut x = 1;
let b;
{
let a = &mut x;
b = &mut *a;
} // a drops here
*b = 2; // it works!
I'm having hard time getting what &*a means, in the point of lifetime.
I don't know how *operator is related to lifetimes of variables.
It seems like b is borrowing x and also a, so that not only x(which is *a) cannot be moved or modified but also a cannot be used.
The error message of compiler is : b borrowing a.
So, I ran the second code.
In my understanding, borrowed data cannot be reassigned or moved, or dropped.
I deliberately made a to drop before b, to make sure that a's lifetime should be longer than b's.
However, second code still works.
So, how can I understand undergoing lifetimes associated with &mut *a?
The important misconception is in your first line of code. The error is not that b borrows a, it's that b borrows *a, meaning it borrows x. Since Rust downgrades and drops references as early as possible, this "double" mutable reference is allowed as long as you don't ever try to use a. However, when using a, the compiler will now warn you that you have a double mutable reference: one borrowing *a (basically x) in the variable a, and one borrowing *a in the variable b.
With that cleared up, your second piece of code makes sense. a can be dropped, because b is just using *a to borrow x, and x has a long enough lifetime to be accessed.
let mut x = 1;
let a = &mut x; // now a is the mutable owner of x
let b = &mut *a; // *a -> x so, now b is the mutable owner of x
*a = 2; // it will not work as a is not the current mutable owner of x
*b = 3; // it will work as a is the current mutable owner of x
let mut x = 1;
let b;
{
let a = &mut x; // now a is the mutable owner of x
b = &mut *a; // *a -> x so, b is the mutable owner of x
} // a dropped but not x
*b = 2; // it will work because b is the current mutable owner of x and x is still in scope.
I'm new to Rust lang and wonder what difference between two blocks in fn main(), can anyone explain in words of lifetime.
Are .as_str() calls change the lifetime of x and y?
Whose lifetime does -> &a' str refer to? a,b,c at lifetime() returning position or z to receive the result?
I consider the variables x and y have the same lifetime scopes in both blocks. And that of z covers the x's and y's.
If (x: &'a str, y: &'a str, z: &'a str) demands same lifetime scope of x,y,z, both blocks should fail.
fn main()
{
let mut z = "123abc";
{//// CAN ONLY SUCCEED WHEN REMOVE THE BRACES OF THIS BLOCK
let x = String::from("ajoisd");
let y = String::from("aso");
z = lifetime(x.as_str(), y.as_str(), z);
}
{//// GOES WELL WITH/WITHOUT BRACES
let x = "ajoisd";
let y = "aso";
z = lifetime(x, y, z);
}
println!("{}", z);
}
fn lifetime<'a>(a: &'a str, b: &'a str, c: &'a str) -> &'a str
{
if a.len() > b.len() {a}
else if a.len() < b.len() {b}
else {c}
}
Strings "ajoisd" and "aso" have the 'static lifetime. They outlive any variable in the program. Variables x and y in the first block live only in this block which is less than the lifetime of z.
I'm trying to write a function that composes two functions. The initial design is pretty simple: a function that takes two functions and returns a composed function which I can then compose with other functions, since Rust doesn't have rest parameters. I've run into a wall built with frustrating non-helpful compiler errors.
My compose function:
fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
where
F: 'a + Fn(A) -> B + Sized,
G: 'a + Fn(B) -> C + Sized,
{
Box::new(move |x| g(f(x)))
}
How I would like to use it:
fn main() {
let addAndMultiply = compose(|x| x * 2, |x| x + 2);
let divideAndSubtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(*addAndMultiply, *divideAndSubtract);
println!("Result is {}", finally(10));
}
The compiler doesn't like that, no matter what I try, the trait bounds are never satisfied. The error is:
error[E0277]: the size for values of type `dyn std::ops::Fn(_) -> _` cannot be known at compilation time
--> src/main.rs:13:19
|
13 | let finally = compose(*addAndMultiply, *divideAndSubtract);
| ^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::ops::Fn(_) -> _`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
note: required by `compose`
--> src/main.rs:1:1
|
1 | / fn compose<'a, A, B, C, G, F>(f: F, g: G) -> Box<Fn(A) -> C + 'a>
2 | | where
3 | | F: 'a + Fn(A) -> B + Sized,
4 | | G: 'a + Fn(B) -> C + Sized,
5 | | {
6 | | Box::new(move |x| g(f(x)))
7 | | }
| |_^
As #ljedrz points out, to make it work you only need to reference the composed functions again:
let finally = compose(&*multiply_and_add, &*divide_and_subtract);
(Note that in Rust, convention dictates that variable names should be in snake_case)
However, we can make this better!
Since Rust 1.26, we can use abstract return types (previously featured gated as #![feature(conservative_impl_trait)]). This can help you simplify your example greatly, as it allows you to skip the lifetimes, references, Sized constraints and Boxes:
fn compose<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| g(f(x))
}
fn main() {
let multiply_and_add = compose(|x| x * 2, |x| x + 2);
let divide_and_subtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(multiply_and_add, divide_and_subtract);
println!("Result is {}", finally(10));
}
Finally, since you mention rest parameters, I suspect that what you actually want is to have a way to chain-compose as many functions as you want in a flexible manner. I wrote this macro for this purpose:
macro_rules! compose {
( $last:expr ) => { $last };
( $head:expr, $($tail:expr), +) => {
compose_two($head, compose!($($tail),+))
};
}
fn compose_two<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
F: Fn(A) -> B,
G: Fn(B) -> C,
{
move |x| g(f(x))
}
fn main() {
let add = |x| x + 2;
let multiply = |x| x * 2;
let divide = |x| x / 2;
let intermediate = compose!(add, multiply, divide);
let subtract = |x| x - 2;
let finally = compose!(intermediate, subtract);
println!("Result is {}", finally(10));
}
Just add references in finally and it will work:
fn main() {
let addAndMultiply = compose(|x| x * 2, |x| x + 2);
let divideAndSubtract = compose(|x| x / 2, |x| x - 2);
let finally = compose(&*addAndMultiply, &*divideAndSubtract);
println!("Result is {}", finally(10));
}
Dereferencing addAndMultiply or divideAndSubtract uncovers a trait object which is not Sized; it needs to either be wrapped in a Box or referenced in order for it to be passed to a function with a Sized constraint.
macro_rules! comp {
($f: expr) => {
move |g: fn(_) -> _| move |x: _| $f(g(x))
};
}
fn main() {
let add1 = |x| x + 1;
let add2 = |x| x + 2;
let add3 = comp!(add1)(add2);
println!("{}", add3(3));
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1c6915d94f7e1e35cf93fb21daceb9ef
fn add(x: i32, y: i32) -> fn() {
let z = x + y;
mul(z, 2);
}
fn mul(x1: i32, y1: i32) -> fn() {
let z1 = x1 * y1;
sub(z1, 2);
}
fn sub(x2: i32, y2: i32) -> (i32) {
let z2 = x2 - y2;
z2
}
fn main() {
let R = add(2, 2);
println!("{}", R);
}
Assigning R to add(2, 2) doesn't work. I need to be able to assign R from add -> mul -> sub which returns z2.
So, the process is add(2, 2) -> mul(4, 2) -> sub(8, 2) thus getting R = 6. How do I go about doing this?
This is the error I get:
error[E0277]: the trait bound `fn(i32): std::fmt::Display` is not satisfied
--> testzz.rs:20:16
|
20 | println!("{}", R);
| ^ the trait `std::fmt::Display` is not implemented for
`fn(i32)`
|
= note: `fn(i32)` cannot be formatted with the default formatter; try using
`:?` instead if you are using a format string
= note: required by `std::fmt::Display::fmt`
It seems to me that you are confused about the syntax of return types of functions. The code compiles perfectly after a couple of minor edits:
fn add(x: i32, y: i32) -> i32 {
let z = x + y;
mul(z, 2)
}
fn mul(x1: i32, y1: i32) -> i32 {
let z1 = x1 * y1;
sub(z1, 2)
}
fn sub(x2: i32, y2: i32) -> i32 {
let z2 = x2 - y2;
z2
}
Note that the return type of all functions is now i32. Returning fn() means something completely different and doesn't make sense in this case. Also, I removed the semicolons at the end of add and mul so Rust knows that they are the return values.