Memory management basics of Rust lang

i need some help with understanding of rust basics and memory basics at all. I think this will be helpful for those who come across this after me. memory adress (1) Here i create a function thats return pointer to a vector. Why there is two different adresses if there must be the same pointer?… Read More Memory management basics of Rust lang

Given an optional mutable reference, can I pass it to another function without moving it?

I am working on a little Rust project where many functions take an optional mutable reference to a struct. For simplicity, let’s say that this struct is a String. So the functions look something like this: fn append_to_string(maybe_string: Option<&mut String>) { if let Some(s) = maybe_string { s.push(‘1’); } } My main function has ownership… Read More Given an optional mutable reference, can I pass it to another function without moving it?

Rust: why does borrowing a reference inside struct borrow the whole struct?

I have the following code: struct MyStruct<‘a>{ data: &’a str, } fn get<‘a>(S: &’a MyStruct<‘a>) -> &’a str{ S.data } fn set<‘a>(S: &’a mut MyStruct<‘a>, x: &’a str){ S.data = x; } fn main(){ let mut S = MyStruct{data: "hello"}; let foo: &str = get(&S); set(&mut S, "goodbye"); dbg!(foo); } This fails to compile because… Read More Rust: why does borrowing a reference inside struct borrow the whole struct?

How to return a struct whose property has a type of &str from a function in rust?

I am trying to do the following // Just removes redundant white space while also splitting the string // with a whitespace. fn split_whitespace(string: &str) -> Vec<&str> { let words: Vec<&str> = string .split_whitespace() .filter(|&word| word != "") .collect(); words } pub fn get_websites_from_hosts(hosts_path: &Path) -> Result<Vec<Website>, std::io::Error> { let hosts_string = read_to_string(hosts_path)?; let result:… Read More How to return a struct whose property has a type of &str from a function in rust?

How to store a mutable borrow with a specified lifetime in an enum?

I want to be able to store a mutable borrow &mut Foo<‘a> inside an enum variant. I can work with the mutable borrow directly just fine, but not with an enum containing the mutable borrow. Extract of simplified code below (‘full’ playground version with ‘broken’ code commented out here). #[derive(Debug)] struct Foo<‘a> { shared_ref: &’a… Read More How to store a mutable borrow with a specified lifetime in an enum?