#Lifetime Issues

12 messages · Page 1 of 1 (latest)

compact grove
#

I'm having tons of issues with lifetime and borrowing right now.

There are 3 big problems:

  1. The body of the snake (?) fn get_adjacent_vertices(&mut self, _set : Set) is moving the Struct, "Set", around which gives me this compiler message move occurs because _set has type Set<'_>, which does not implement the Copy trait

I've tried to implement Copy using both #[derive(Copy)] and impl Copy for Set {} , but they both spit out errors complaining that "Set cannot have this trait".

If I borrow it claims that the arguments of the function are incorrect.

  1. &_set.set[neighbor_x][neighbor_y] claims that "Borrowed value _set.set does not live enough". I have zero ideas on how to fix this issue (I've never used lifetimes on my own)

  2. {if !(neighbor.is_solid()) {self.adjacent.push(neighbor)}} has the compiler claiming that the lifetime may not live long enough argument requires that 1 must outlive 2. It also says that main.rs(41, 41): has type Set<1> /ln main.rs(41, 30): has type &mut Vertex<2>. again, I don't have any idea how to solve this

wind star
#

1: check_adjacent_vertex doesn't actually need to consume _set, and as such should take _set: &Set instead. The same is true of get_adjacent_vertices, actually. You don't just need to borrow where you call the function, you also need to change its definition to accept a borrow.

2: this error indirectly stems from the first one. The issue is that self.adjacent stores data that lives for 'a, but you're trying to give it a reference to a local variable, which is less than 'a. The fix would be to take as an argument _set: &'a Set, so you can have neighbor be a &'a Vertex<'a> as required.

3: get your errors from cargo check: IDEs tend to remove all the useful parts from the error message. This is actually the same error as 2, I believe, just showing you the other part.

#

--

By the way, _-prefixed variables are conventionally intentionally unused variables, so you probably shouldn't name a used variable _set

#

Also, a word of warning for the future: actually using these types will be difficult. It looks like you're trying to create a graph, but due to the lifetimes the only possible way to make things work out will be an arena allocator crate: you've written things so that every element must be dropped at the exact same time

#

What you may want instead is to make Vertex store a Vec<usize> for adjacent, then you index into Set's vectors to access your data

#

On a related note

#

-book

wind star
#

If you find the book overly wordy, check out alternatives in #beginner-resources . The topics you've asked about seem to stem from a lack of understanding of borrowing. That's understandable, but learning it properly will serve you better 🙂

compact grove
wind star
#

The thing you need to express is that the argument needs to be borrowed for as long as self needs, which is to say for Vertex's lifetime parameter