Questions tagged [lifetime]
A variable's life-time is the time during which the variable is bound to a specific memory location. The life time starts when the variable is allocated and ends when it is deallocated.
1,845
questions
-1
votes
1
answer
28
views
Implementation is not general enough in async fn
The following code fails to compile:
use std::marker::PhantomData;
use async_trait::async_trait;
#[async_trait(?Send)]
trait App {
async fn call_app<'req>(&self, req: &'req str);
}
...
0
votes
2
answers
54
views
Rust mutably borrowed lifetime issue
This is en excerpt from my actual code, but the issue is the same. I cannot borrow the staging_buffer in Buffer::from_data as mutable, and I cannot figure out why this is the case. Why isn't the ...
1
vote
0
answers
34
views
Accessing internal lifetimes in async code (`FnOnce` is not general enough)
I want to make a function that creates some internal state, lets a user to modify it, and then proceeds to do other stuff. This works fine in the normal case but I also want to give the user an ...
1
vote
1
answer
79
views
What's the idiomatic way of consuming read-only struct's fields many times in the same function?
I'm just starting with Rust and since I'm a person who learns by doing I would like to fully understand the idiomatic way of solving cases like this in Rust.
Many replies I got in chat are all the ...
5
votes
1
answer
76
views
How can I couple the lifetimes of two variables?
The following code compiles and runs fine, but does not work as intended (compare the comments in the code). I believe the reason is that the lifetime of is ends with getFileIter, so the stream buffer ...
0
votes
1
answer
55
views
How to save a closure in a Struct with a mutable reference to outside the struct?
I am trying to make an stack machine where that can take a closure for the output like this:
pub struct VirtualMachine {
stack: Vec<isize>,
code: Vec<Op>,
code_pointer: usize,
...
0
votes
1
answer
27
views
mismatched types between method and lifetime-generic parameter
I expect the following Rust code to work
struct Expression<'a> {
s: &'a str,
}
impl<'a> Expression<'a> {
fn foo(e: Expression<'a>, _: Expression<'a>) -> ...
1
vote
1
answer
61
views
How to interpret Rust error E0495 on the lifetimes of a closure and a variable borrowed by the closure
I'm trying to understand a lifetime error. I've reduced the code to this short, albeit nonsensical playground:
type Value = Vec<i32>;
type MemberList<'a> = Box<dyn Iterator<Item = &...
0
votes
1
answer
47
views
How do I define the lifetime for a tokio task spawned from a class?
I'm attempting to write a generic set_interval function helper:
pub fn set_interval<F, Fut>(mut f: F, dur: Duration)
where
F: Send + 'static + FnMut() -> Fut,
Fut: Future<Output = (...
0
votes
0
answers
11
views
Problem with lifetimes. How to track a lifetime error in de-serialization and fix it? [duplicate]
I'm writing a small crate to manage the app's config in rust. The idea is to write a toml file that is taken by the module and then this makes the config accessible for all app.
So, I have this module ...
0
votes
1
answer
76
views
Creating an instance of struct that contains a reference to some locally created struct
I have a library crate with few structs that contain references to each other:
pub struct A ();
pub struct B<'l> (pub &'l A);
pub struct C<'l> (pub &'l B<'l>);
I can use ...
1
vote
1
answer
39
views
Rust passing closures and they lifetime
Hi I try to pass my closure to mockall crate returning function in following way:
pub fn set_dialog_game_selection(dialogs: &mut Box<MockAsk>, steam_id: String) {
dialogs
....
0
votes
0
answers
40
views
How to solve to create field mutable references by methods
I have the following simple tuple struct Tuple:
struct Tuple<T>(T, T);
I could create mutable reference separately by field directly:
#[test]
fn create_mut_fields_directly() {
let mut p = ...
0
votes
2
answers
47
views
Generic function that sums Vec<T> for types implementing use std::iter::Sum;
I'm trying to create something with Command pattern and came up with something like this:
trait Command {
fn execute(&self);
}
struct PrintSum {
params: Vec<i32>
}
impl Command for ...
0
votes
1
answer
31
views
Rust - Specifying a Lifetime Parameter for the Borrow Trait
I have a struct (DataSource) that holds some data (&[u8]), and a custom iterator that iterates over it.
struct DataSource<'a> {
data: &'a Vec<u8>,
}
struct MyIterator<'a>...
0
votes
0
answers
89
views
rust : missmatch between given lifetimes and expected lifetimes
I want to make a sdl2 texture manager with bevys ECS but I am running into problems with lifetimes that I don't quite understand or know how to fix.
// the texturemanager a texturecreator to create ...
0
votes
1
answer
28
views
access reference in struct causes cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
I'm implementing a web service using tonic grpc crate.
Here is the my code:
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::sync::Mutex;
fn main() {
let my_struct = MyStruct {...
0
votes
1
answer
51
views
Rust lifetime - "does not live long enough" error happens when I create instance
I'm writing a toy OS.
I can't fix following lifetime error.
My code fails to compile due to does not live long enough
error[E0597]: `fb_config` does not live long enough
--> src/main.rs:37:45
|...
0
votes
1
answer
39
views
Why rust told me that a reference still borrowed at the end of main function?
As you can see in the following code, I have two traits, one is called Hittable, and the other is called Material (I have been studying the book "ray-tracing-in-one-weekend", but use Rust).
...
0
votes
1
answer
37
views
constructing completely private and anonymous static singleton
I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this:
namespace {
class curl_guard {
public:
curl_guard()
{
...
3
votes
1
answer
69
views
Why is rustc's suggestion here wrong?
I'm trying to implement the following trait, where the <'baz> is required for a later impl<'baz> Baz<'baz> for T where T: OtherTrait†.
trait Baz<'baz>: Clone {
fn baz(&'...
0
votes
0
answers
18
views
How do you return a reference with a lifetime from an Iterator implementation in Rust? [duplicate]
I tried to implement Iterator, which is to yield a tuple containing references to the underlying Vec entries.
fn main() {
let mut storage_person_cat = StoragePersonCat {
persons: Vec::new()...
13
votes
1
answer
298
views
Is it defined behavior to explicitly call a destructor and then use placement new to reconstruct it?
This is very similar to Correct usage of placement-new and explicit destructor call but tighter in scope:
If I have a type, S, for which std::is_nothrow_default_constructible_v<S> and std::...
0
votes
2
answers
45
views
Rust lifetimes in async wrapper for sync code
I am trying to create a Stream using a camera with a blocking capture method. The blocking call is wrapped with blocking::unblock.
use futures::stream;
use rscam::{Camera, Config};
fn frame_stream() -...
0
votes
1
answer
55
views
Rust – moved variable forbids to borrow itself ("dropped here while still borrowed")
I'm trying to write a program that generates mathematical expressions and then evaluates them. Expressions can contain primitive operations (plus, minus, etc.) or other sub-expressions that consist of ...
2
votes
2
answers
114
views
what is impl Trait + 'lifetime [duplicate]
I am reading the async book. In section async lifetimes there is a code snippet whose grammar I am not familiar with:
fn foo_expanded<'a>(x: &'a u8) -> impl Future<Output = u8> + '...
0
votes
1
answer
55
views
Type mismatch in closure arguments + closure lifetimes
In Yew, I am attempting to bind a callback to the window resize event, triggering a Msg::Resize update. I have encountered: E0631 Type mismatch in closure arguments.`
Expanded version of the code can ...
0
votes
2
answers
61
views
Why can't Rust downgrade my lifetime but instead complains about type mismatch?
Consider the following struct:
struct State<'a> {
parent: Option<&'a mut State<'a>>,
// ...
}
My state stores some values that I might need later. Now I want to ...
2
votes
1
answer
33
views
Rust – cannot infer an appropriate lifetime when returning trait object from trait method
I'm trying to make something like immutable Dictionary trait that can be added new items (references) into and used without affecting the previous version. Minimal example:
#[derive(Clone)]
pub struct ...
0
votes
1
answer
48
views
Can a trait's impl specify a lifetime that comes from a method's input argument?
For a type
pub struct Child<'a> {
buf: &'a mut [u8],
}
I can define a trait and implement the trait for the type but with a lifetime that is bound to a calling function's context (not ...
1
vote
1
answer
49
views
How to give a reference an explicit lifetime in rust? [duplicate]
I'm trying to return a Result<(), &str> in rust, where the &str has embedded data about any errors which have occurred. For example, say I have the following code:
struct Foo {
pub ...
0
votes
1
answer
41
views
Function as trait with output type polymorphic in lifetime
How do I express a constraint like
fn<F: 'static> apply_to_foos(f: F)
where
for<'a> F: fn(&'a mut Foo) -> impl Future<Output = Bar> + 'a
{
...
}
(The above expression doesn't ...
0
votes
1
answer
60
views
Temporary lifetime extension mixed with copy elision object on clang
I have an issue in a project of mine that uses aggregate types to extend the lifetime of temporaries in a relatively safe manner by making aggregates that contain references uncopyable and unmovable, ...
0
votes
1
answer
44
views
Trouble with lifetimes on iterator that mutates iterable
I'm making a "sorted iterator" which takes a slice of unsorted items and outputs them in sorted order and sorts the underlying slice as you go using heap sort. The trouble is there is a ...
4
votes
1
answer
72
views
Lifetime of the returned range-v3 object in C++
I want to make a function that works like np.arange(). With range-v3, the code is
auto arange(double start, double end, double step){
assert(step != 0);
const auto element_count = static_cast&...
0
votes
1
answer
69
views
Is there a nicer way to create a vector from indexed data in rust?
I have the problem, that I get some data from an iterator (specifically a bevy Query) and part of that data is an index. I now want to create a vector with this data, where every element is placed at ...
0
votes
1
answer
65
views
storing arrays of string literals without size - std::initializer_lists
I am exploring methods for storing arrays of literals (any type) without sidecar size information. I've sketched some approaches but for each have some lingering questions. Here I use std::...
0
votes
1
answer
62
views
Lifetime extension of temporary objects: what is the full expression containing a function call?
Introduction
Say there is a Container class which stores Widget objects.
There is an iterator class in charge of navigating such container. This iterator class (MyIterator) takes a const-reference to ...
0
votes
1
answer
108
views
cannot return value referencing temporary value
I'm new to Rust, and have the following code which doesn't compile:
fn cells(&self) -> impl Iterator<Item = &Vector2<isize>> {
match self {
Kind::O => [(0, 0), (0,...
1
vote
1
answer
204
views
How to pass arguments by reference when call python in c++ with pybind11
I'm using PyBind11 to run a Python interpreter, and I need to call a Python function in c++ with some pointer arguments.
According to the docs of pybind11, it looks like that a argument being passed ...
2
votes
1
answer
50
views
What are the rules for lifetimes in Rust when using boxed trait objects?
The code below doesn't compile with error E0597: borrowed value (two) doesn't live long enough.
fn main() {
let one = String::from("one");
let mut _it: Box<dyn Iterator<Item=...
1
vote
1
answer
40
views
Force a struct to outlive another struct
I have two structs. The first, "parent" struct holds a resource that needs explicit cleanup, which I am handling by deriving the Drop trait. The second, "child" struct is retrieved ...
0
votes
1
answer
67
views
Why can I elide the lifetime of the return type in one case but another one requires to choose a lifetime explicitly?
Here, I must give App a full lifetime and cannot elide it (App<'_>):
struct App<'a> {
items: StatefulList<'a, (&'a str, &'a str, usize)>,
}
impl App<'_> {
fn ...
0
votes
1
answer
36
views
How do I specify an associated type with a lifetime parameter?
I have this trait representing the ability to render text (e.g. HTML) from a template, and an associated type TemplateData to contain the data the template needs:
trait Template {
type ...
0
votes
1
answer
46
views
How to fix "Closure may outlive the current function"
I've this code:
pub fn find_saddle_points(input: &[Vec<u64>]) -> Vec<(usize, usize)> {
let mut row_max: Vec<HashSet<usize>> = vec![HashSet::new(); input.len()];
let ...
0
votes
2
answers
72
views
Why is explicitly annotating the lifetime required in the first case, but not in the second?
Here, the annotating 'a explicitly for items is required:
struct App<'a> {
items: StatefulList<'a, (&'a str, &'a str, usize)>,
}
impl<'a> App<'a> {
fn new(...
0
votes
1
answer
94
views
Blazor server issue with nested DI objects' scope
I have been using Blazor for a few months now, and got use to when and how components render and re-rendered.
I however am struggling with scopes of DI injected objects inside other DI injected ...
4
votes
1
answer
62
views
Why does this mutual referencing structures work in Rust with specified lifetimes?
Why does the following code compiles?
I would expect the Rust compiler to tell me
"borrowed value does not live long enough" when setting the reference (store.barber.set(Some(&barber));
...
3
votes
1
answer
81
views
Trait associated type lifetime and self
I have a struct that wraps a std::cell::Ref and provides access by reference to the underlying value. Something like this:
use std::cell::Ref;
struct IntAccess<'a> {
i: Ref<'a, i32>,
}...
1
vote
2
answers
110
views
Borrowed value does not live long enough with Vec of Cow
Here is a minimalist example of a problem I'm encountering. The following code produces the below error. I just encountered this Cow thing and I don't know how it works exactly. How should I fix this?
...