Lifetimes are perhaps the hardest thing to understand when first approaching Rust. Today I’m going to create a lifetime error and demonstrate two strategies for fixing it. If you’re very new to rust, you may wish also to read the (beautifully titled) post Rust Lifetimes for the Unitialised first, as well as Strategies for Returning References in Rust.
To get started, we’re going to consider two Ruby implementations that are equivalent:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# first version | |
my_collection = SomeCollection.new | |
(1..10).each do |item| | |
value = "value number #{item + 1}" | |
my_collection.insert(value) | |
end | |
# second version | |
my_collection = SomeCollection.new | |
values = [] | |
(1..10).each do |item| | |
value = "value number #{item + 1}" | |
values.push(value) | |
end | |
values.each { |v| my_collection.insert(v) } |