Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
I have a min-heap of i32 in Rust, and I want to calculate the sum of its elements and store it in i32.
let mut total_sum = 0;
for current in min_heap {
total_sum = current + total_sum;
}
I am getting the following error when compiling:
cannot add `{integer}` to `Reverse<i32>`
You can simply call the sum method on your iterator after mapping Reverse<i32>'s inside your heap to their inner values.
let total_sum: i32 = min_heap.into_iter()
.map(|i| i.0)
.sum();
Some advices:
Avoid mutations;
Don't use x = x + y, use x += y instead;
Don't use camelCase in function and variable names;
Don't use new-line braces.
You can use the tuple accessor, .0, or use destructuring.
let mut total_sum = 0;
for current in min_heap {
total_sum += current.0;
}
Or with destructuring:
let mut total_sum = 0;
for Reverse(current) in min_heap {
total_sum += current;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 days ago.
Improve this question
I want to have a global variable _c that can change based on different situation.
This is some of my code:
fn test(&mut self){
let mut _c:string = "".to_string();
let mut dictionary = HashMap::new();
match c {
zero => {
bits = if resb > 0 { 1 } else { 0 };
bits |= bits * power;
power <<= 1;
}
let bits_u16: Vec<u16> = vec![bits.clone() as u16];
_c = String::from_utf16(&bits_u16).unwrap();
dict_size += 1;
dictionary.insert(dict_size, Value::Str(&_c));
let mut n: i32 = _c.parse().unwrap();
n = n - 1;
_c = n.to_string();
enlarge_in = -1;
}
The error said
Can not assigned to _c because it is borrowed
Is there any way to fix this problem and still keep _c updated?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
In rust, order of the functions do not matter unlike C or C++ where main function should be at the end. But it is not the same for closures and I wonder why
For example, this code compiles:
fn main(){
println!("{}", add_up(1));
}
fn add_up(x: i32) -> i32{
x + y
}
const y:i32 = 1;
and this code does not compile:
fn main(){
let add_up = |x:i32| x + y;
let y = 1;
println!("{}", add_up(1));
}
I know in the first one y is a global variable and that is not a fair comparison but this is the example I can think of at the moment. The main point is, generally order does not matter in rust (where is main located or where is add_up located) but not the same for closures. Why?
The difference between a local variable (which can be captured by a closure) and a constant or static is that the latter don't have "scope", they are available before the program starts and last for as long as the program. A variable, on the other hand, has a clear scope - a place where it's introduced and a place where it's destructed, and attempt to use it outside that region cannot work.
For example, if it were allowed to capture variables that are not yet created might result in non-sensical code like this:
let c = || x;
println!("{}", c()); // what does this print?
let x = some_function_that_takes_user_input();
let x = x + 1;
{
let x = 100;
}
A static or a const, on the other hand, doesn't have this issue because it's not created at any time, it always exists for as long as the program.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a function that is supposed to search for primes within a given range. (The algorithm is not important; please ignore the fact that it is very inefficient.)
use std::thread;
use std::sync::Mutex;
use std::convert::TryInto;
/// Takes the search range as (start, end) and outputs a vector with the primes found within
/// that range.
pub fn run(range: (u32, u32)) -> Vec<u32> {
let mut found_primes: Mutex<Vec<u32>> = Mutex::new(Vec::new());
let num_threads: usize = 8;
let num_threads_32: u32 = 8;
let join_handles: Vec<thread::JoinHandle<()>> = Vec::with_capacity(num_threads);
// ERROR: `found_primes` does not live long enough
let vec_ref = &found_primes;
for t in 0..num_threads_32 {
thread::spawn(move || {
let mut n = range.0 + t;
'n_loop: while n < range.1 {
for divisor in 2..n {
if n % divisor == 0 {
n += num_threads_32;
continue 'n_loop;
}
}
// This is the part where I try to add a number to the vector
vec_ref.lock().expect("Mutex was poisoned!").push(n);
n += num_threads_32;
}
println!("Thread {} is done.", t);
});
}
for handle in join_handles {
handle.join();
}
// ERROR: cannot move out of dereference of `std::sync::MutexGuard<'_, std::vec::Vec<u32>>`
*found_primes.lock().expect("Mutex was poisoned!")
}
I managed to get it working with std::sync::mpsc, but I'm pretty sure it can be done just with mutexes. However, the borrow checker doesn't like it.
The errors are in comments. I (think I) understand the first error: the compiler can't prove that &found_primes won't be used within a thread after found_primes is dropped (when the function returns), even though I .join() all the threads before that. I'm guessing I'll need unsafe code to make it work. I don't understand the second error, though.
Can someone explain the errors and tell me how to do this with only Mutexes?
The last error is complaining about trying to move the contents out of the mutex. The .lock() returns a MutexGuard that only yields a reference to the contents. You can't move from it or it would leave the mutex in an invalid state. You can get an owned value by cloning, but that shouldn't be necessary if the mutex is going away anyway.
You can use .into_inner() to consume the mutex and return what was in it.
found_primes.into_inner().expect("Mutex was poisoned!")
See this fix and the other linked fix on the playground.
This question already has answers here:
Why do I need rebinding/shadowing when I can have mutable variable binding?
(2 answers)
Closed 4 years ago.
From my understanding, shadowing in Rust allows you to use the same variable by using let and re-declaring the variable e.g.
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
but, if you make the variable mutable, doesn't that mimic shadowing e.g.:
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
x = 7;
println!("The value of x is: {}", x);
In example 1 & 2, where is the variable stored, in the stack or heap?
All values in your example are stored on the stack. In example 1, a new value is pushed onto the stack for each let statement.
It looks like you got the example from The Rust Programming Language. Maybe read this paragraph again for emphasis:
The other difference between mut and shadowing is that because we’re
effectively creating a new variable when we use the let keyword again,
we can change the type of the value but reuse the same name.
This question already has answers here:
What's the difference between placing "mut" before a variable name and after the ":"?
(4 answers)
Closed 6 years ago.
What is the difference between
let y = &mut 5;
*y += 1;
let x = *y + 1;
and
let mut y = 5;
y += 1;
let x = y + 1;
They return the same result via println!, but I can't decide which one is preferable.
Given your simple example of binding a variable to one or the other, then calling println! locally, there really isn't much difference in the result (as you've noted).
A mutable value vs a mutable reference becomes more clear when you cross function boundaries. Have a look at this code:
fn main() {
let mut x = &mut 5;
do_work(x);
println!("{}", x);
}
fn do_work(n: &mut u32) {
*n += 5;
}
What do you think it prints? Here it is on the playground
Now look at this code:
fn main() {
let mut x = 5;
do_work(x);
println!("{}", x);
}
fn do_work(mut n: u32) {
n += 5;
}
What do you think this prints? Here it is on the playground
The answers are:
The top code block prints 10. The bottom code block prints 5.
Using the mutable reference means you're referencing the place in memory where the variable x is stored. Across function boundaries, you're able to change the value stored in memory there. When the method returns and println! hits.. the value of x is updated.
In this specific example, x is a u32, which implements the Copy trait. When you pass x into the do_work method, a copy of x is made. In the body of the do_work method, n += 5 adds 5 to the copy .. and does not reference the original block of memory at all.
...can't decide which one is preferable.
That depends entirely on use-case. Do you need to reference the original memory when crossing a function boundary? If you have marked your variable as mutable, there is a high chance that you do want to reference the original memory in the hopes of updating it. In that case, you would use a mutable reference. If you're just mutating a variable locally within a function.. then you won't require a reference.