1,895 questions
5
votes
1
answer
176
views
Why does the presence of the drop method cause the borrow checker to become unhappy?
While trying to write an API inspired by the structure of std::thread::scope, I ran across the following problem. This function compiles fine (playground):
use std::marker::PhantomData;
pub struct ...
1
vote
1
answer
112
views
Why does 'borrowed valued does not live long enough' error appear when storing value and its reference in a struct?
I'm aware it is not much possible nor recommended to have both a field that owns a value, and another one that stores a reference to the same value in a struct.
I was experimenting a bit with a more ...
2
votes
1
answer
67
views
Handling of async callback that mutates the environment
I'm trying to create a little utility that simplifies the execution of repetitive work. This would be almost trivial in memory managed languages, but gets unnervingly complex in Rust. I'd call myself ...
5
votes
1
answer
75
views
Why does this code that moves a closure into another closure and returns both even compile?
I have the following code:
fn test() -> (impl FnMut(&mut u8), impl FnMut(&mut u8)) {
let a = |v: &mut u8| {*v = 0};
let b = move |v: &mut u8| { a(v); println!("{}&...
1
vote
1
answer
62
views
How to fix this lifetime-related error happen when using the Fn trait?
Context
I'm trying to learn Rust by just reading the book and working through the problems in Advent of Code (the 2024 edition). Just to make it harder, I decided to practice TDD while I do it.
To ...
4
votes
1
answer
76
views
If the return value of a function has the same lifetime as one of the arguments, then the return value is considered a borrow of the argument?
Where in Rust's specification does it say that if the returned reference of a function has the same lifetime as one of the reference arguments, then the returned reference is considered a borrow of ...
1
vote
0
answers
74
views
Why does the rust compiler keep a mutable reference here? [duplicate]
Consider the following program:
struct RNG {
numbers: Vec<u32>,
}
impl RNG {
pub fn new() -> RNG {
RNG { numbers: vec![] }
}
pub fn generate_random_numbers(&mut ...
2
votes
2
answers
70
views
Is there a way to release and recapture references in closures while iterating?
I have code analogous to:
struct L {
length: usize,
count: usize,
}
impl L {
fn iter(&self, ns: impl Iterator<Item=usize>) -> impl Iterator<Item=usize> {
ns....
1
vote
1
answer
141
views
Why does this conditional assignment give a borrow error when inside a loop but not outside?
This code
// No particular meaning, just MVCE extracted from larger program
pub fn foo(mut v: Vec<i32>) {
let x = &v[0];
for _ in [0, 1] {
if *x == 0 {
v[0] = 0;
...
2
votes
4
answers
391
views
How to define Rust HashMap where the keys are refences to the values?
I am porting some of my more complex C++ code over to Rust as a way to learn the language. One thing I have is a map of values keyed by a std::string held inside the value type, to avoid copying the ...
0
votes
0
answers
39
views
Shared logic to return both a mutable and non-mutable reference in Rust [duplicate]
I'm fairly new to Rust, and this is a pattern that I've observed a few times. In the contrived example below, I have a struct with two fields of the same type: first: Vec<u32> and second: Vec<...
-1
votes
1
answer
68
views
How do I move a Sender object out of a mutable reference to a Vector of tuples of Strings and Sender Objects?
This is not a solution to my problem. The suggested answer replaces the values with Nones. I quite literally require the size of my vector to reduce.
MRE:
use tokio::sync::mpsc;
#[tokio::main]
async ...
0
votes
0
answers
33
views
How to correctly implement back references to parent objects in Rust [duplicate]
I have been working on a DOM object in Rust and to insure document integrity I want to implement back references to parent objects, prevent circular references, etc.
Minimally my code looks like this:
...
0
votes
1
answer
68
views
Why does this rust borrow checker doesn't reject this code? [duplicate]
The following doesn't compile as I expected, as y is dropped before r.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main()...
1
vote
2
answers
114
views
What are the differences between these two borrowing cases?
I am making a game in Rust and have a few different trait GameModules that are a part of the main App.
pub struct AppView<'a> {
pub frame_delta: &'a f64,
pub area: &'a Rect
}
...
2
votes
1
answer
67
views
Problem with lifetimes when implementing custom mutable Iterator for struct
I want to implement a mutable Iterator for my custom struct as following:
#[derive(Debug, Clone)]
pub struct Message<'a> {
content: &'a str,
}
#[derive(Debug, Clone)]
pub struct ...
1
vote
1
answer
90
views
Difficulty understanding the logic of borrowing rules
I'm reading "the book", and wanted to test my understanding of the borrowing rules in chapter slicing.
I was impressed with (my assumption of) how the borrow checker associated what I passed ...
2
votes
1
answer
103
views
How to specify lifetime for referencing a value from an iterator in order to peek its contents?
I'm trying to learn Rust. A pattern that I've used in other languages is to wrap an iterator with a data structure that allows me to call .peek() or .next(). The result looks like an iterator, except ...
1
vote
0
answers
37
views
Counter-intuitive double-borrow [duplicate]
I have been trying to implement my own Option::get_or_insert_with, with a twist: the function that produces the value to insert in the Option is fallible. This was my first, most reasonable-looking ...
0
votes
2
answers
82
views
Lifetime of `Ref<'a, &mut [u8]>` is not actualy 'a
I have the following two external functions:
try_borrow_data(&AccountInfo<'a>) -> Result<Ref<&mut [u8]>, ProgramError>
read(data: &[u8]) -> Option<&Self>
...
0
votes
1
answer
224
views
How do I encapsulate waiting for a `tokio::sync::watch::Receiver` to be `Some`?
I'd like to write an async function recv_some which takes a watch::Receiver<Option<T>>, waits for the value to be Some, and returns something which Deref's to T. For reasons I sort of ...
0
votes
0
answers
41
views
Why do I have to borrow the reference if the return value is already a reference? [duplicate]
In the following code I use the square bracket operator on a HashMap:
let mut my_hash_map: HashMap<u32, String> = HashMap::new();
my_hash_map.insert(5, "value".to_string());
let my_val ...
0
votes
0
answers
48
views
What lifetime does this function have when not annotated? [duplicate]
I'm learning Rust and I wrote this somewhat contrived example.
#[derive(Debug)]
struct Foo<'a> {
x: i32,
s: &'a String,
}
impl<'a> Foo<'a> {
fn new(s: &String) -&...
0
votes
2
answers
120
views
Can't understand how did the unique immutable borrows in captures work
I've been reading the section Unique immutable borrows in captures of the book The Rust Reference and can't figure out why the code is illegal:
let mut b = false;
let x = &mut b;
{
let mut c = ...
0
votes
1
answer
45
views
Rust Errors: Cannot borrow as mutable more than once at a time, cannot borrow as immutable because it is also borrowed as mutable
I have the following example code:
let mut errors: Vec<String> = Vec::new();
let msg1 = "message 1".to_string();
let msg2 = "message 2".to_string();
let msg3 = "message ...