Reputation: 441
I'm new to Rust and I'm still struggling with borrowing and move concepts.
To set the context, I'm using a library (namely MVT ) that uses following construct to create a layer:
let mut tile = Tile::new(4096);
let layer = tile.create_layer("First Layer");
let b = GeomEncoder::new(GeomType::Linestring, Transform::default())
// ... add some data to b
let mut feature = layer.into_feature(b);
feature.set_id(1);
feature.add_tag_string("key", "value");
let layer = feature.into_layer();
tile.add_layer(layer)?;
The most interesting pieces are layer.into_feature(b)
which takes ownership of the layer and later feature.into_layer()
which returns ownership of the layer again.
This sounds really strange to me. Is this some known concept/design pattern in Rust? I would expect, that the onwership of layer will remain untouched (i.e. it is not moved but borrowed).
The problem I have with that piece of code is, that I would like to keep a HashMap
of Layer
s to avoid creating layers with the same name twice, i.e. sth. like this:
let mut layers = HashMap::new();
let layer = layers.entry(layer_name).or_insert(tile.create_layer(layer_name));
But this fails with below error, which makes sense b/c layer.into_feature(b)
is moving the layer out of the HashMap
which it shouldn't (IMO).
error[E0507]: cannot move out of `*layer` which is behind a mutable reference
--> src/main.rs:39:23
|
39 | let mut feature = layer.into_feature(b);
| ^^^^^^---------------
| | |
| | `*layer` moved due to this method call
| move occurs because `*layer` has type `Layer`, which does not implement the `Copy` trait
So to summarize my question: Is there a way to get the library code working with a hashmap or do I need to change the library to not do that ownership ping-pong?
Upvotes: 1
Views: 88