Why i cant read variable that using Copy trait while its mutably borrowed
⚓ Rust 📅 2026-02-06 👤 surdeus 👁️ 7Hi,i tried to compile that code:
let mut x = 10;
let x_ref = &mut x;
let y = x;
*x_ref = 5;
and i got a error bout i cant use "x" while there is mut reference to x.
my question is, why i got that error? (i know about rust borrow rules, and about when we have &mut we cannot use this variable), but why? okay i understand that if we writing in a multi-thread code, there can be a data races, but this is single thread code, what bad can happen??
i think like that:
x is i32, i32 using a Copy trait, this is a single-thread code, what bad can happen??
i read a similar posts about my question, they talking about optimization in answers about reordering a instructions, and by making optimization in my code that can looks like that:
let mut x = 10;
let x_ref = &mut x;
*x_ref = 5;
let y = x;
y is 5, but we expected that y gonna be 10 etc...
but really? optimization is that "stupid"? okay by using that logic i can tell that code is unsafe:
let mut vector = vec![1];
vector.push(2);
vector.push(3);
vector.push(4);
cause optimization can reorder push calling and we can get a vector that looks like that:
1,4,2,3
but we expected:
1,2,3,4
that sounds stupid, and i don't trust to that answer.
maybe compiler doesn't know bout we writing in single thread code? that sounds better than optimization answer, but i don't think so.
maybe my code is too simple to be unsafe in single-thread, but why compiler doesn't know that my code is too simple to be unsafe in single-thread?
well please give me answer to this question, if you can provide me a single thread code that looks like mine and explain why its gonna be unsafe if its gonna compile, that will be super answer to my question.
8 posts - 4 participants
🏷️ Rust_feed