Why can't you store a value and a reference to it in the same struct in Rust?
Hi everyone! I started learning Rust and encountered a problem that really puzzled me. I'm trying to write a struct that stores some data and at the same time a reference to that data inside itself. For example, I want to create a struct that contains a string and its first character — a reference to that string.
Here's what I'm trying to do:
```rust
struct MyStruct {
data: String,
first_char: &str, // reference to data
}
fn main() {
let text = String::from("Hello");
let first = &text[..1];
let s = MyStruct { data: text, first_char: first };
println!("{}", s.first_char);
}
```
The compiler gives an error: `error[E0382]: borrow of moved value: 'text'`. I understand that when I move `text` into the struct, I can no longer use `first` because it references
No answers yet.
Log in to leave an answer