Fixing a Simple Lifetime Error in Rust

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:

# 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) }

view raw
two_examples.rb
hosted with ❤ by GitHub

Continue reading “Fixing a Simple Lifetime Error in Rust”