Cannot infer an appropriate lifetime for lifetime parameter cloning trait object - rust

The duplicates of this question don't seem to solve things for me. The following code gives me errors:
use std::collections::HashMap;
use std::thread;
pub trait Spider : Sync + Send {
fn add_request_headers(&self, headers: &mut Vec<String>);
}
pub struct Google {}
impl Spider for Google {
fn add_request_headers(&self, headers: &mut Vec<String>) {
headers.push("Hello".to_string())
}
}
fn parallel_get(spiders: &HashMap<String, Box<Spider>>) -> std::thread::JoinHandle<()> {
let thread_spiders = spiders.clone();
thread::spawn(move || {
let headers = &mut vec![];
let spider = thread_spiders.get("Google").unwrap();
spider.add_request_headers(headers);
})
}
fn main() {
let spiders = HashMap::new();
let spider = Box::new(Google{});
spiders.insert("Google", spider);
}
Run on the playground here.
I get:
rustc 1.14.0 (e8a012324 2016-12-16)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> <anon>:18:34
|
18 | let thread_spiders = spiders.clone();
| ^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the block at 17:87...
--> <anon>:17:88
|
17 | fn parallel_get(spiders: &HashMap<String, Box<Spider>>) -> std::thread::JoinHandle<()> {
| ^
note: ...so that types are compatible (expected &&std::collections::HashMap<std::string::String, Box<Spider>>, found &&std::collections::HashMap<std::string::String, Box<Spider + 'static>>)
--> <anon>:18:34
|
18 | let thread_spiders = spiders.clone();
| ^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure#<anon>:19:19: 23:6 thread_spiders:&std::collections::HashMap<std::string::String, Box<Spider>>]` will meet its required lifetime bounds
--> <anon>:19:5
|
19 | thread::spawn(move || {
| ^^^^^^^^^^^^^
I think it's telling me that it can't automatically infer the lifetime of thread_spiders because it needs to be 'static to live long enough for the thread, but it can't outlive 'a which is the lifetime of the input parameter.
The thing is, I can clone other objects in parallel_get and they get moved into the new thread without issue. But for some reason thread_spiders seems to trip up the compiler. It should have a lifetime of 'a if I'm correct and then get moved into the thread closure.
I've tried adding explicit lifetime parameters to parallel_get but haven't been able to get anything working. How can I make this code compile?

The error message is quite confusing in this case, but notice a double ampersand here:
(expected &&std::collections::HashMap<std::string::String, Box<Spider>>, found &&std::collections::HashMap<std::string::String, Box<Spider + 'static>>).
It looks like it tries to clone the reference. I assume you wanted to clone the entire HashMap. Calling clone explicitly as Clone::clone(spiders) gives much clearer error message:
error[E0277]: the trait bound `Spider: std::clone::Clone` is not satisfied
error[E0277]: the trait bound `Spider: std::marker::Sized` is not satisfied
--> error_orig.rs:19:26
|
19 | let thread_spiders = Clone::clone(spiders);
| ^^^^^^^^^^^^ the trait `std::marker::Sized` is not implemented for `Spider`
|
= note: `Spider` does not have a constant size known at compile-time
= note: required because of the requirements on the impl of `std::clone::Clone` for `Box<Spider>`
= note: required because of the requirements on the impl of `std::clone::Clone` for `std::collections::HashMap<std::string::String, Box<Spider>>`
= note: required by `std::clone::Clone::clone`
You are calling Clone::clone on Box<Spider>, an owned trait object.
How do I clone a HashMap containing a boxed trait object? illustrates that it can be implemented by introducing a cloning method to your trait, like so:
pub trait Spider: Sync + Send {
fn add_request_headers(&self, headers: &mut Vec<String>);
fn clone_into_box(&self) -> Box<Spider>;
}
impl Clone for Box<Spider> {
fn clone(&self) -> Self {
self.clone_into_box()
}
}
#[derive(Clone)]
pub struct Google {}
impl Spider for Google {
fn add_request_headers(&self, headers: &mut Vec<String>) {
headers.push("Hello".to_string())
}
fn clone_into_box(&self) -> Box<Spider> {
Box::new(self.clone())
}
}
How to clone a struct storing a trait object? suggests creating a separate trait for this polymorphic cloning method.

Related

Rust - Lifetimes - Understanding Lifetime Error for mutable reference to self

I'm sure this is a duplicate, but I can't find a question which matches my question, exactly since I have a couple extra requirements because I have to adhere to some traits that I can't control.
Here is my code. I apologize for the sort of convoluted example, but this was the most I could minimize it as I am trying to implement a custom serialization format using the serde library.
// Doesn't really matter what this struct contains, it just needs an owning method
struct SideStruct;
impl SideStruct {
fn something_side<A: TraitA>(&self, aval: A) {
println!("something sideways :)");
aval.something_a(42)
}
}
trait TraitA {
fn something_a(&mut self, data: u32); // this would be the meat of my logic
}
// Note that this struct has an explicit lifetime
struct MainStruct<'a> {
refr: &'a mut u32
}
// Note that I implement for a mutable reference to MainStruct
impl<'a> TraitA for &'a mut MainStruct<'a> {
fn something_a(&mut self, data: u32) {
// Completely arbitrary, can safely ignore this function body
*self.refr += data;
println!("We're finally doing something: {}", self.refr);
}
}
// Implementing for MainStruct itself
impl<'a> MainStruct<'a> {
// Note, I can't change the signature for this function because it implements a trait
fn something_indirect(&mut self, ss: &SideStruct) {
// here is where the error occurs!
ss.something_side(self)
}
}
fn main() {
let mut base_val: u32 = 42;
let ss = SideStruct {};
let mut main_val = MainStruct { refr: &mut base_val };
main_val.something_indirect(&ss);
}
This is the error I got:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:28:27
|
28 | ss.something_side(self)
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
--> src/main.rs:27:27
|
27 | fn something_indirect(&mut self, ss: &SideStruct) {
| ^^^^^^^^^
note: ...so that the expression is assignable
--> src/main.rs:28:27
|
28 | ss.something_side(self)
| ^^^^
= note: expected `&mut MainStruct<'a>`
found `&mut MainStruct<'a>`
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/main.rs:26:6
|
26 | impl<'a> MainStruct<'a> {
| ^^
note: ...so that the types are compatible
--> src/main.rs:28:12
|
28 | ss.something_side(self)
| ^^^^^^^^^^^^^^
= note: expected `<&mut MainStruct<'a> as TraitA>`
found `<&mut MainStruct<'_> as TraitA>`
For more information about this error, try `rustc --explain E0495`.
I don't know what the compiler means when it states that note: first, the lifetime cannot outlive the anonymous lifetime defined here.... Does it mean that some constraint forces self to not outlast the method something_indirect? That makes no sense. Also the message so that the expression is assignable confuses me. MainStruct should not be assigned when something_side is called on it right? Since I implemented TraitA for a mutable reference to MainStruct, shouldn't I be able to call something_side with a mutable reference to MainStruct by passing self? Anyways, thanks for the help, and have a great day!
The trouble is that in order to use the method defined, you must borrow the MainStruct as mutable with an anonymous lifetime. In the code you wrote, you not only borrow the things within MainStruct for 'a, but also MainStruct itself. This is unnecessary since the borrow has an inferred lifetime. You can fix this by removing the 'a in the trait impl
impl<'a> TraitA for &mut MainStruct<'a> {
/*...*/
}
This should do the exact same thing, but removes the bug. The bug is trying to tell you that the code you wrote is buggy, because it borrows MainStruct using a lifetime in the struct itself.

How to get a reference to a struct with lifetime annotations from a trait object? [duplicate]

I ran into a lifetime problem with a little game. The below code represents a very boiled down version of the update loop.
I need the container mutable reference to get references to other game objects or to create new ones or trigger a functionality.
For that reason, I need the Any trait to be able to cast the trait to a struct, so in my GameObj trait I added an as_any method, but this resulted in a lifetime issue.
use std::any::Any;
trait GameObj<'a> {
fn as_any<'b>(&'b self) -> &'b (dyn Any + 'a);
fn update(&mut self, cont: &mut container);
}
struct object<'a> {
content: &'a String,
}
impl<'a> GameObj<'a> for object<'a> {
fn as_any<'b>(&'b self) -> &'b (dyn Any + 'a) {
return self;
}
fn update(&mut self, cont: &mut container) {
let val = cont.get_obj().unwrap();
let any = val.as_any();
}
}
struct container<'a> {
data: Vec<Box<dyn GameObj<'a> + 'a>>,
}
impl<'a> container<'a> {
fn get_obj<'b>(&'b self) -> Option<&'b Box<dyn GameObj<'a> + 'a>> {
return Some(&self.data[0]);
}
}
pub fn main() {
let a = String::from("hallo");
let b = String::from("asdf");
{
let abc = object { content: &a };
let def = object { content: &b };
let mut cont = container { data: Vec::new() };
cont.data.push(Box::new(abc));
cont.data.push(Box::new(def));
loop {
for i in 0..cont.data.len() {
let mut obj = cont.data.remove(0);
obj.update(&mut cont);
cont.data.insert(i, obj);
}
}
}
}
playground
When I try to build the code, it results in the following error message.
If I comment out/delete let any = val.as_any(); in the update function it compiles fine.
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:18:24
|
18 | let val = cont.get_obj().unwrap();
| ^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #3 defined on the method body at 17:5...
--> src/main.rs:17:5
|
17 | / fn update(&mut self, cont: &mut container) {
18 | | let val = cont.get_obj().unwrap();
19 | | let any = val.as_any();
20 | | }
| |_____^
= note: ...so that the types are compatible:
expected &container<'_>
found &container<'_>
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the declared lifetime parameter bounds are satisfied
--> src/main.rs:19:23
|
19 | let any = val.as_any();
| ^^^^^^
How I can make this work without using 'static, or why is this impossible?
Any is declared trait Any: 'static and can only store 'static types. So in order to make dyn Any + 'a a well-formed type, your as_any method was given an implicit 'a: 'static bound, leading to the lifetime error you showed.
If not for this restriction, you would be able to break safety by putting in an 'a type into an Any and getting out a 'static type, because TypeId can’t tell the difference—lifetimes are erased during compilation. See the discussion on RFC 1849 for more information.
You should think more carefully about why you want to use Any. It’s almost never what you actually want. Perhaps something as simple as an enum type of all the different object types you might want to store would satisfy your use case better?
If you really want to use Any, then you’ll need to find a way to make your types 'static. Rc (or Arc, if threads are involved) is often helpful for this purpose; for example, you could have your object store Rc<String> (or better, Rc<str>) instead of &'a String.

How to return an iterator over the keys of a HashMap from a trait implementation?

I'm trying to build a simple graph library in Rust. There is a trait Graph that any graph must implement. This trait has only one function at the moment, nodes, which allows iteration of the graph's nodes using a for-in loop.
An implementation of Graph, MapGraph, is a lightweight wrapper around a HashMap. MapGraph must implement the Graph trait method nodes. I'm having problems getting this to work.
Here's the code for Graph:
pub trait Graph<N> {
fn nodes(&self) -> Box<dyn Iterator<Item = &N>>;
}
And here's the code for MapGraph:
use std::collections::HashMap;
use crate::rep::Graph;
pub struct MapGraph<N> {
map: HashMap<N, HashMap<N, ()>>
}
impl<N> MapGraph<N> {
pub fn new(map: HashMap<N, HashMap<N, ()>>) -> Self {
MapGraph { map }
}
}
impl<N> Graph<N> for MapGraph<N> {
fn nodes(&self) -> Box<dyn Iterator<Item=&N>> {
let keys = self.map.keys();
Box::new(keys)
}
}
The compiler gives this error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:19:29
|
19 | let keys = self.map.keys();
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
--> src/lib.rs:18:5
|
18 | / fn nodes(&self) -> Box<dyn Iterator<Item = &N>> {
19 | | let keys = self.map.keys();
20 | |
21 | | Box::new(keys)
22 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:19:20
|
19 | let keys = self.map.keys();
| ^^^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<(dyn std::iter::Iterator<Item = &N> + 'static)>
found std::boxed::Box<dyn std::iter::Iterator<Item = &N>>
I've found other references to this error, but those cases don't seem to look like the one I have here.
I'm using Box because the Graph trait has a function that itself returns a trait. What is the correct way to return an Iterator (or any other trait)? gives this approach as one option, and I haven't been able to implement any of the the others. If there's another way to do this, that would be fine.
What are my options for resolving this specific problem?
It works if you explicitly specify that the trait object (dyn Iterator) that you are returning contains references that are tied to the lifetime of self.
Without adding this bound, the compiler cannot infer from the function signature that the iterator cannot be used after self is moved or destroyed. Because the compiler cannot infer this, it cannot safely use self.map.keys() in the function's output.
Working example with this bound added:
pub trait Graph<N> {
fn nodes<'a>(&'a self) -> Box<dyn Iterator<Item = &N> + 'a>;
}
use std::collections::HashMap;
pub struct MapGraph<N> {
map: HashMap<N, HashMap<N, ()>>,
}
impl<N> MapGraph<N> {
pub fn new(map: HashMap<N, HashMap<N, ()>>) -> Self {
MapGraph { map }
}
}
impl<N> Graph<N> for MapGraph<N> {
fn nodes<'a>(&'a self) -> Box<dyn Iterator<Item = &N> + 'a> {
let keys = self.map.keys();
Box::new(keys)
}
}
Playground
I had thought that a bound of Item = &'a N would also be required, but I guess that's already covered by the "+ 'a"...
N.B. that to make sense of an error like:
expected std::boxed::Box<(dyn std::iter::Iterator<Item = &N> + 'static)>
found std::boxed::Box<dyn std::iter::Iterator<Item = &N>>
you have to understand that the compiler, for ergonomic reasons, automatically adds a + 'static lifetime qualifier to any unqualified trait object. This means that an unqualified Box<dyn MyTrait> is transformed by the compiler into a Box<(dyn MyTrait + 'static)>, which in turn means that the object cannot contain any references except those that last for the lifetime of the entire program.
With this in mind you can see why self.map.keys() does not fit this strict bound, and a more specific explicit bound is required.

Why can't I call a method after destructuring a variable but I can if I access the field directly?

The following didn't compile:
use std::any::Any;
pub trait CloneBox: Any {
fn clone_box(&self) -> Box<dyn CloneBox>;
}
impl<T> CloneBox for T
where
T: Any + Clone,
{
fn clone_box(&self) -> Box<dyn CloneBox> {
Box::new(self.clone())
}
}
struct Foo(Box<dyn CloneBox>);
impl Clone for Foo {
fn clone(&self) -> Self {
let Foo(b) = self;
Foo(b.clone_box())
}
}
Error message:
error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements
--> src/lib.rs:20:17
|
20 | let Foo(b) = self;
| ^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 19:5...
--> src/lib.rs:19:5
|
19 | / fn clone(&self) -> Self {
20 | | let Foo(b) = self;
21 | | Foo(b.clone_box())
22 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:20:17
|
20 | let Foo(b) = self;
| ^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `&std::boxed::Box<dyn CloneBox>` will meet its required lifetime bounds
--> src/lib.rs:21:15
|
21 | Foo(b.clone_box())
|
However if change the code in clone() from Foo(b.clone_box()) to Foo(self.0.clone_box()), it compiles without problem. In theory, field access should be the same as pattern matching, but why does pattern matching have lifetime issues?
In my real code, the data is in an enum, not a struct, so pattern matching is the only option.
TL;DR: Dereference the value before calling the method:
Foo((*b).clone_box())
With let Foo(b) = self, the type of b is &Box<(dyn CloneBox + 'static)>. The method call is effectively
Foo(<&Box<dyn CloneBox + 'static> as CloneBox>::clone_box(&b))
This value cannot be made into the trait object Box<dyn CloneBox + 'static> because of the local reference. Amusingly, I believe this would be recursively using the blanket implementation if the compiler allowed it.
With self.0.clone_box(), the method call is effectively:
Foo(<dyn CloneBox as CloneBox>::clone_box(&**b)
We could write this as Foo((&**b).clone_box()) to be explicit, but since there's no intermediate implementations, Foo((*b).clone_box()) is sufficient.
See also:
What are Rust's exact auto-dereferencing rules?

Lifetime issue when using the Any trait to get references to structs containing references

I ran into a lifetime problem with a little game. The below code represents a very boiled down version of the update loop.
I need the container mutable reference to get references to other game objects or to create new ones or trigger a functionality.
For that reason, I need the Any trait to be able to cast the trait to a struct, so in my GameObj trait I added an as_any method, but this resulted in a lifetime issue.
use std::any::Any;
trait GameObj<'a> {
fn as_any<'b>(&'b self) -> &'b (dyn Any + 'a);
fn update(&mut self, cont: &mut container);
}
struct object<'a> {
content: &'a String,
}
impl<'a> GameObj<'a> for object<'a> {
fn as_any<'b>(&'b self) -> &'b (dyn Any + 'a) {
return self;
}
fn update(&mut self, cont: &mut container) {
let val = cont.get_obj().unwrap();
let any = val.as_any();
}
}
struct container<'a> {
data: Vec<Box<dyn GameObj<'a> + 'a>>,
}
impl<'a> container<'a> {
fn get_obj<'b>(&'b self) -> Option<&'b Box<dyn GameObj<'a> + 'a>> {
return Some(&self.data[0]);
}
}
pub fn main() {
let a = String::from("hallo");
let b = String::from("asdf");
{
let abc = object { content: &a };
let def = object { content: &b };
let mut cont = container { data: Vec::new() };
cont.data.push(Box::new(abc));
cont.data.push(Box::new(def));
loop {
for i in 0..cont.data.len() {
let mut obj = cont.data.remove(0);
obj.update(&mut cont);
cont.data.insert(i, obj);
}
}
}
}
playground
When I try to build the code, it results in the following error message.
If I comment out/delete let any = val.as_any(); in the update function it compiles fine.
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:18:24
|
18 | let val = cont.get_obj().unwrap();
| ^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #3 defined on the method body at 17:5...
--> src/main.rs:17:5
|
17 | / fn update(&mut self, cont: &mut container) {
18 | | let val = cont.get_obj().unwrap();
19 | | let any = val.as_any();
20 | | }
| |_____^
= note: ...so that the types are compatible:
expected &container<'_>
found &container<'_>
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the declared lifetime parameter bounds are satisfied
--> src/main.rs:19:23
|
19 | let any = val.as_any();
| ^^^^^^
How I can make this work without using 'static, or why is this impossible?
Any is declared trait Any: 'static and can only store 'static types. So in order to make dyn Any + 'a a well-formed type, your as_any method was given an implicit 'a: 'static bound, leading to the lifetime error you showed.
If not for this restriction, you would be able to break safety by putting in an 'a type into an Any and getting out a 'static type, because TypeId can’t tell the difference—lifetimes are erased during compilation. See the discussion on RFC 1849 for more information.
You should think more carefully about why you want to use Any. It’s almost never what you actually want. Perhaps something as simple as an enum type of all the different object types you might want to store would satisfy your use case better?
If you really want to use Any, then you’ll need to find a way to make your types 'static. Rc (or Arc, if threads are involved) is often helpful for this purpose; for example, you could have your object store Rc<String> (or better, Rc<str>) instead of &'a String.

Resources