Iterating over a Vec<Vec<T>> struct [duplicate] - rust

This question already has answers here:
How do I extract a value from a tuple struct?
(3 answers)
Closed 5 months ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
With the below code snippet, Rustc gives the error cannot index into a value of type Matrix<T>.
What would be the proper way to access the vectors inside the Matrix struct in such cases?
pub struct Matrix<T>(pub Vec<Vec<T>>);
impl<T> Add for Matrix<T> {
fn add(self, other_matrix: Self) -> Option<Self> {
let mut vector_1 = vec![];
for x in 0..self.len() {
for y in 0..self[x].len() {
let total = self[x][y] + other_matrix[x][y];
vector_1.push(total);
}
// ... //
}
}
}
Any advice would be much appreciated!

You use identifier.order syntax to access a member of a tuple struct. In your case, it becomes self.0, and your snippet becomes like this:
for x in 0..self.0.len() {
for y in 0..self.0[x].len() {
let total = self.0[x][y] + other_matrix.0[x][y];
vector_1.push(total);
}
...

Related

Is there an idiomatic way to convert empty Vec to None? [duplicate]

This question already has answers here:
How do I idiomatically convert a bool to an Option or Result in Rust?
(4 answers)
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
I have a closure in a filter_map that ends in this if statement:
if my_vec.is_empty() {
None
} else {
Some(my_vec)
}
Is there a simple way to convert an empty Vec into either a None or a Some(my_vec)?
There is a function in impl bool called then which converts a bool to an option.
let opt = (!my_vec.is_empty()).then(|| my_vec);
There is also then_some, available in nightly.
#![feature(bool_to_option)]
fn main() {
let my_vec: Vec<i32> = vec![];
let _opt = (!my_vec.is_empty()).then_some(my_vec);
}
Since you mentioned filter_map, what about changing
sth.filter_map(|item| {
let my_vec = some_operation(item);
if my_vec.is_empty() {
None
} else {
Some(my_vec)
}
})
to
sth
.map(|item| some_operation(item))
.filter( |vec| !vec.is_empty())
According to official doc, Rust's iterators are zero-cost abstraction, so you can do this without extra cost.

How do we have 2 mutable references to the same value existing at the same [duplicate]

This question already has answers here:
Do mutable references have move semantics?
(1 answer)
What are non-lexical lifetimes?
(1 answer)
Closed 2 years ago.
I have the following code that compiles and runs without any issues -
#[derive(Debug)]
pub struct A<'a> {
field: &'a mut String
}
fn main() {
let mut b = "Hello".to_owned();
let a = A { field: &mut b };
let c = A { field: a.field };
c.field.push('+');
a.field.push('+');
//println!("{:?}", c);
// println!("{:?}", a);
}
But I am confused as to why this code is working, or even compiling, for the following reasons -
It seems like we are holding two mutable references to the same object b. This is evident since both c.field.push('+'); and a.field.push('+'); succeed.
Why does this statement - let c = A { field: a.field };, not move field out of A (since mutable references are not copyable) and invalidate A?

What does ‘mut’ before a function's parameter name mean? [duplicate]

This question already has answers here:
What's the difference between placing "mut" before a variable name and after the ":"?
(4 answers)
Why does Rust allow mutation through a reference field using an immutable binding?
(1 answer)
Closed 2 years ago.
After a lot of struggle getting used to borrowing, references, ownership etc. and trying to follow the compiler's suggestions how to fix certain issues, I ended up with the following pair of functions in my first bit of Rust code.
fn adjust_culture(mut cooperating_families: Vec<&mut Family>) {
for f in cooperating_families.iter_mut() {
mutate_culture(f);
}
let family: Option<&&mut Family> = cooperating_families.choose(&mut rand::thread_rng());
match family {
None => {},
Some(f) => {
let target: Culture = f.culture;
for f2 in cooperating_families {
f2.culture = target;
}
}
}
}
fn mutate_culture(family: &mut Family) {
if family.seasons_till_next_mutation > 0 {
family.seasons_till_next_mutation -= 1;
}
if family.seasons_till_next_mutation == 0 {
let i: u8 = rand::thread_rng().gen_range(0, culture_dimensionality);
family.culture ^= 1 << i;
}
}
The second one makes sense to me, and preventing it from gaining additional borrowing decoration was a major point getting me to this solution. But adjust_culture confuses me: Why did the compiler suggest to add the mut before cooperating_families in the function's parameter definition?
I thought I would just have to pass a mutable binding to access the fields of the individual families, but with another function
fn extract_resources(patch: Patch, group: Vec<&mut Family>, total_labor_here: usize) -> KCal {
let labor: u8 = group.iter().map(|f| {f.effective_size as u8}).sum();
let resources_extracted = resources_from_patch(
patch, labor as usize, total_labor_here - labor as usize,
false);
for family in group {
family.stored_resources +=
resources_extracted * family.effective_size as f32 / labor as f32
}
return resources_extracted
}
Rust told me that group does not need to be mutable, and now I'm quite confused.
Which bit of adjust_culture has a chance to change the value of cooperating_families instead of just the objects inside it? How do I avoid that from happening – my mental idea of the semantics says is should not happen?

How do I create a unique ID for a Rust object? [duplicate]

This question already has answers here:
Generate sequential IDs for each instance of a struct
(2 answers)
How to check if two variables point to the same object in memory?
(1 answer)
Closed 4 years ago.
I would like to give my object a unique ID (to be able to compare them). I figured to do something along these lines:
pub struct Player {
id: i32,
score: usize,
}
impl Player {
fn new() -> Player {
let mut player = Player {};
player.id = &player as *const i32;
player
}
}
I run into the problem that I need to set the variables when defining the Player, but there is no memory address at that point.
I could make the id mutable, but there is no need to change the variable after initialisation.
How can I do something like this?

Compiler not happy with reading from dropped struct's field after writing to it [duplicate]

This question already has answers here:
Why does compilation not fail when a member of a moved value is assigned to?
(2 answers)
Why is assigning to a member of a pointer still valid after the pointer is moved?
(1 answer)
Closed 4 years ago.
#[derive(Debug)]
struct A {
x: i32
}
fn main() {
let mut x = A{x: 1};
drop(x);
// this is fine?
x.x = 100;
// this is not? ERROR: "use of moved value x.x"
println!("{}", x.x);
}
I've read some answers here that says if you re-initialize the struct after move, then you can use it again. I am re-initializing it fully here and yet can't use it. Why is this feature (ability to write to struct fields after move) even there?

Resources