Creating an immutable temporary object that `Copy`s a mutable reference contained by an immutable object could (?) but doesn't work
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
struct Thing<'a> {
mut_ref_value: &'a mut u8
}
fn func<'a>(thing: &'a Thing<'a>) {
func(&Thing {mut_ref_value: thing.mut_ref_value})
}
fn main() {
println!("Hello, world!");
}
I expected to see this happen: For the code to compile (albeit not do anything useful). Because the Thing constructed in Func is an immutable temporary, the fact that thing is immutable shouldn't restrict using its &mut u8 since it can only ever be used as a &u8. I am not entirely certain that reasoning checks out but I'm having a hard time thinking of a way it isn't.
It breaks the "don't have two mutable references to the same thing" rule but I don't think breaking it here could cause issues.
The code I ran into this in uses thing.mut_ref_value to create an actually different version of Thing so this isn't just a random edge case nobody'd ever run into.
Instead, this happened:
error[E0596]: cannot borrow `*thing.mut_ref_value` as mutable, as it is behind a `&` reference
--> src/main.rs:6:33
|
6 | func(&Thing {mut_ref_value: thing.mut_ref_value})
| ^^^^^^^^^^^^^^^^^^^ `thing` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
5 | fn func<'a>(thing: &'a mut Thing<'a>) {
| +++
Meta
rustc --version --verbose:
rustc 1.81.0 (eeb90cda1 2024-09-04)
Backtrace
N/A
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the provided snippet with the reported rustc 1.81.0 version and compare its behavior with current compiler versions. Investigate the borrow-checking and reference-copying rules involved; done requires a documented decision on whether this should compile and, if accepted, a compiler regression test demonstrating the intended behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100