I'm a newbie.
How to change a struct immutable reference field?
I try to clone it then change it, but report error.
Code:
struct A<'a> {
scores: &'a [u32]
}
fn main () {
let scores = &[1,2,3];
let a = A{scores};
let mut s = a.scores.clone();
s.sort();
println!("{:?}", s);
}
Report:
8 | let mut s = a.scores.clone();
| ----^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default
error[E0596]: cannot borrow `*s` as mutable, as it is behind a `&` reference
--> src/bin/main.rs:9:5
|
8 | let mut s = a.scores.clone();
| ----- help: consider changing this to be a mutable reference: `&mut [u32]`
9 | s.sort();
| ^ `s` is a `&` reference, so the data it refers to cannot be borrowed as mutable
Putting references in structs is a beginner mistake. Almost always you should use owned types in structs.
struct<'a> is an advanced usage for special cases — don't use it until you're proficient with ownership. & it is for creating temporary views into data that is already owned somewhere else, and it can't be used to store or modify any data, except when using interior mutability.
Nope. If you have a immutable borrow, and the type doesn't contain interior mutability (UnsafeCell type used for Mutex, etc.), then there's no way at all, never ever to mutate anything via that reference.
&[u32] type is absolutely untouchable in all cases in Rust, and there's no way around that, and never will be. You have to use a different type (e.g. copy the data elsewhere)
If you try to hack around it with unsafe code (such as raw pointers or transmute), it will cause Undefined Behavior, and you'll lose all Rust's safety guarantees, and the compiler reserves the right to generate invalid code and cause crashes.