1,897 questions
0
votes
2
answers
68
views
Dropping optional borrow in structure
I am writing a scripting language in rust, and I'm pretty new to the language.
When I compile source into byte code I move the compiled symbols (Chunk) out of the function.
I am also lazy and don't ...
3
votes
0
answers
77
views
Returning mutable references and lifetime in rust [duplicate]
I am trying to develop a linear algebra library in rust. So, as part of it I am writing code that iterates through a n-dimensional array and returns mutable references. It's like writing a view for a ...
4
votes
2
answers
123
views
Rust global variable lifetime safety
This is a pattern I want to be able to use in my code to have global variables that contain non-static references. Is it memory safe? If not, how can I make it so?
use std::cell::Cell;
pub struct ...
5
votes
1
answer
180
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 ...
5
votes
1
answer
132
views
Rust specifying a trait and associated type are valid for the lifetime inside a function
I am using the winnow crate to write a parser and am struggling with
adding tests due to lifetime conflicts.
The basic setup I have is a stateful stream:
// The primary stream type
type SStream<'i, ...
1
vote
1
answer
119
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 ...
0
votes
1
answer
141
views
how to avoid "borrow of moved value" with subpattern match
Edit: added a second part of the question below.
I am getting the error "borrow of moved value" here, but the thing being moved is an &mut Containee, so I didn't expect it to cause a ...
2
votes
1
answer
68
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 ...
4
votes
2
answers
189
views
Understanding how Rust elides lifetimes with mutable references
I want to understand lifetimes and the elision rules better.
Suppose we want to extend a Vec<i32> (really Vec<&i32>)
fn extend_vector(
v: &mut Vec<&i32>,
x: &...
5
votes
1
answer
79
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
2
answers
102
views
Rust borrow checker: "cannot borrow `...` as immutable because it is also borrowed as mutable [E0502] immutable borrow occurs here"
I wanted to implement the Merge Sort algorithm, but I am having trouble with the borrow checker rules.
The compiler gives me the hint:
cannot borrow *lst as immutable because it is also borrowed as ...
1
vote
1
answer
66
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 ...
1
vote
2
answers
89
views
Comparing Swift's and Rust's function signatures
I want to check my understanding of how Swift and Rust handle function parameters.
From what I’ve seen, Swift has two main parameter modes:
Pass by value, immutable: f(x: T) and
Pass by reference, ...
4
votes
1
answer
77
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 ...
0
votes
0
answers
74
views
Non-bitwise move or `Move` trait? [duplicate]
In Rust, how can I define&manipulate objects that cannot be just copied bit-by-bit when they're moved?
For example, an object that contains a relative pointer (i.e. a pointer whose target is ...
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 ...
1
vote
2
answers
95
views
Question about Rust bracket operator plus ampersand
The following snippet is from the (Brown University ver.) Rust book
fn largest<T>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > ...
2
votes
2
answers
76
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....
-2
votes
2
answers
116
views
Converting Option<String> to Option<&str> in match statement
I have a function that takes in a Option<&str>, but my var is currently a Result<String> that I have converted to Option<String> in a match statement.
let geom_source= std::fs::...
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;
...
1
vote
0
answers
118
views
Why does Miri report UB in this safe looking manual String::from_raw_parts usage after Vec::set_len(0)?
I'm experimenting with manually handling the deallocation of Strings stored in a Vec<String> by taking raw parts and calling String::from_raw_parts after setting the vec's length to 0.
The ...
2
votes
4
answers
406
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 ...
3
votes
3
answers
172
views
Given a pointer x, why does setting y = x pass ownership, but y = &*x does not?
I am trying to understand the concept of ownership better. The code below does not compile:
fn main() {
let x = Box::new(1);
let y = x;
println!("{}", x);
}
This makes sense, because ...
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<...
3
votes
2
answers
132
views
Insert to a HashMap if the key doesn't already exist, without cloning the key if it already exists?
I have a HashMap whose key type holds a heap allocation. I don't know if the HashMap already contains a particular key, and I would like to insert a new entry if the key doesn't already exist. How ...
-1
votes
1
answer
69
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
1
answer
74
views
modify function to also return a mutable reference to a field of &mut self
Here is a rust function from my project
llms-client::gemini::types::Session::update()
pub(super) fn update(&mut self, reply: &str) {
let history = &mut self.history;
if ...
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:
...
4
votes
1
answer
93
views
Why does a refcell borrowed within an expression live longer than intended (while borrowing to a variable works)
I ran into a surprising (to me) error while using RefCell and I want to understand better why this is happening. I had something like this code below where I have a while let block consuming a mutable ...
0
votes
1
answer
71
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()...
0
votes
0
answers
32
views
Nested mutable and immutable borrows in rust [duplicate]
MRE:
enum MRE_Enum {
variant1,
variant2,
}
struct MRE_Struct {
dummy1: Vec<MRE_Enum>,
dummy2: isize,
}
// Private functions together
impl MRE_Struct {
fn foo(&mut self) ...
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
}
...
0
votes
0
answers
37
views
In rust, why is shadowing an object with a reference to itself valid? [duplicate]
Sorry, I'm just starting to learn rust, and still don't understand many of its features.
I was suprised that this rust code compiles without warning or error:
fn main() {
let s1 = String::from(&...
2
votes
1
answer
70
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 ...
0
votes
0
answers
53
views
Lifetime issue when implementing reconnecting socket?
I'm building a client for an API targeting an embedded system. I'm using the reqwless HTTP client library running on top of esp-hal based stack. On top of reqwless, I want to implement automatic ...
1
vote
1
answer
91
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 ...
1
vote
1
answer
113
views
Borrowing from dereference vs. Direct Borrowing in Rust
Env: rustc 1.82.0 (f6e511eec 2024-10-15)
Question: Dereferencing vs. Direct Borrowing in Rust
I’m confused about the difference between *&T and T in borrowing. The following code compiles with ...
2
votes
1
answer
104
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 ...
2
votes
1
answer
92
views
Call Box<dyn FnMut> as struct field
I have a struct called UpgradeProperties that takes a Box<dyn FnMut(&mut Self)> as a field. However, when I try to create a function to call it I get an error.
Relevant Code:
pub struct ...
1
vote
0
answers
38
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
0
answers
42
views
Cannot borrow `*self` as mutable more than once at a time [duplicate]
The Error
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src\scanner\mod.rs:103:17
|
45 | impl<'a> Scanner<'a> {
| -- lifetime `'a` defined ...
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>
...
4
votes
0
answers
61
views
Why does the borrow checker seem to keep a reference borrowed in a match statement even after the end of the block? [duplicate]
Here is some code that causes my issue as succinctly as possible:
struct Parent {
child: Option<Box<Parent>>,
}
fn main() {
let mut parent = &mut Parent { child: None };
...
0
votes
1
answer
226
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
1
answer
90
views
Best practice for self vs. static struct function to avoid duplicate borrow issue
I have a problem I found a solution to but it is so ugly that there must be a better "idiomatic" way to solve it (I'm from a C++/Java background so I still fell the urge to make everything ...
0
votes
0
answers
42
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
33
views
How to invoke multiple methods on a mutable borrow in Rust [duplicate]
Basically I am having hard time understanding why calling multiple methods on a mutable reference can cause the borrow checker to err.
Example snippet:
use std::collections::HashMap;
struct MainState ...
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
1
answer
65
views
How can I remove all of the outgoing edges for a given node in a GraphMap?
I would like to know how to remove all of the outgoing edges for a given node in a directed GraphMap.
I've tried this:
use petgraph::{graphmap::GraphMap, visit::EdgeRef, Directed, Direction};
fn main()...
0
votes
2
answers
121
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 = ...