generic deserialisation (type-punning) of structs (fighting with the borrow checker)
Date : March 29 2020, 07:55 AM
wish of those help The argument bs: &[u8] is a slice, and is borrowed. This is a form of temporary ownership, you can't move the data out. *p2 does just that, it moves ownership of that data out. You need to clone it: fn from_byte_slice<T: Clone>(bs: &[u8]) -> Option<T> {
if bs.len() != std::mem::size_of::<T>() {
None
} else {
let p: *const u8 = &bs[0];
let p2: *const T = p as *const T;
unsafe {
Some((*p2).clone())
}
}
}
|
Rust Implement Methods -- Borrow with "getter" method inside mutable borrow method
Date : March 29 2020, 07:55 AM
will be helpful for those in need Consider the following example program: , You need to save self.peek() into a temporary fn write(&mut self) {
let tmp = self.peek();
self.output.push(tmp);
}
let tmp1 = &mut self.output;
let tmp2 = self.peek();
Vec<u8>::push(tmp1, tmp2);
|
How can I define a generic struct in Rust without one of the fields being of the generic type?
Date : March 29 2020, 07:55 AM
may help you . PhantomData can be used "to mark things that "act like" they own a T". So, you could write: pub struct Images<T: ImageFormat> {
path: String,
phantom: PhantomData<T>, // mark that Image "acts like" it owns a T
}
Images {
path: ...
phantom: PhantomData,
}
|
Rust error: borrow occurs after drop a mutable borrow
Date : March 29 2020, 07:55 AM
Does that help Your understanding of how scopes and lifetimes work is correct. In Rust Edition 2018, they enabled non-lexical lifetimes by default. Prior to that, the lifetime of inc would have been to the end of the current lexical scope (i.e. the end of the block) even though its value was moved before that. If you can use Rust version 1.31 or later, then just specify the edition in your Cargo.toml: [package]
edition = "2018"
rustc --edition 2018 main.rs
#![feature(nll)]
let mut c = 0;
{
let mut inc = || { c += 1; c };
drop(inc);
// scope of inc ends here
}
println!("{}", c);
|
is there a way to use a generic type alias as the generic type for a function in Rust
Date : March 29 2020, 07:55 AM
I hope this helps you . Nope since Rust doesn't enforce type bounds on type aliases. Your example is equivalent to this: type DebuggableFromStr<T> = T;
|