Is there place there is examples for every use case ? That would very usefull to learn.
Here is a problem I am running into.
I have a structure with a open file and UUID that i want to initialize once, globally and hence am using lazy_static to store it.
Having trouble using it though, method functions that use the file/uuid field to write to the file and in invoking the method
#[macro_use(lazy_static)]
extern crate lazy_static;
use std::io::prelude::*;
use std::fs::File;
pub struct Tracker {
pub file: File,
pub uuid: String,
}
impl Tracker {
pub fn init() -> Tracker {
Tracker {
file : File::create("/tmp/file.data").unwrap(),
uuid : "MYUUID".to_string(),
}
}
pub fn wisk_reportop(self: &Self, value: &str) {
write!(self.file, "{}: {}\n", self.uuid, value).unwrap();
self.file.flush().unwrap();
}
}
lazy_static! {
pub static ref TRACKER : Tracker = Tracker::init();
}
fn main() {
TRACKER.wisk_reportop("Hello World!");
}
with the above code I get
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow `self.file` as mutable, as it is behind a `&` reference
--> src/main.rs:21:16
|
20 | pub fn wisk_reportop(self: &Self, value: &str) {
| ----- help: consider changing this to be a mutable reference: `&mut Tracker`
21 | write!(self.file, "{}: {}\n", self.uuid, value).unwrap();
| ^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
error[E0596]: cannot borrow `self.file` as mutable, as it is behind a `&` reference
--> src/main.rs:22:9
|
20 | pub fn wisk_reportop(self: &Self, value: &str) {
| ----- help: consider changing this to be a mutable reference: `&mut Tracker`
21 | write!(self.file, "{}: {}\n", self.uuid, value).unwrap();
22 | self.file.flush().unwrap();
| ^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
If I use
&mut self
instead, as in
pub fn wisk_reportop(&mut self, value: &str) {
I get
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow data in a dereference of `TRACKER` as mutable
--> src/main.rs:32:5
|
32 | TRACKER.wisk_reportop("Hello World!");
| ^^^^^^^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `TRACKER`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
What am I doing wrong here. A fix would be greatly appreciated.
But help in explaining the 2 cases why they are wrong along with the fix would be awesome.
Thanks,
Sarvi