Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
error[E0507]: cannot move out of X which is behind a shared reference.
Making a Nannou App that draws a line to the screen.
My model only contains the window itself and a vector of tuples describing the points and color.
Similar to this example(under Drawing Lines) I want to use polyline()
to draw a vector of (point, color) tuples to the screen. Unlike the example I want the vector to not be generated in the view()
function but to be part of the model.
(empty update function is added for completeness' sake)
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
// so this is a window id called _window -- I guess.
_window: window::Id,
my_line: Vec<(Point2, Hsl)>,
}
fn model(app: &App) -> Model {
let _window = app.new_window().size(512, 512).view(view).build().unwrap();
// where I define the line that I want to draw to the screen.
let my_line = vec![
(pt2(1.3, 2.5), hsl(28.0 / 360.0, 1.0, 0.68)),
(pt2(-7.0, 2.5), hsl(28.0 / 360.0, 1.0, 0.68)),
];
Model { _window, my_line }
}
fn update(_app: &App, _model: &mut Model, _update: Update) {
// empty for now
}
The problem is when wanting to draw the line to the screen in the view()
function.
fn view(app: &App, _model: &Model, frame: Frame) {
let draw = app.draw();
draw.background().color(GRAY);
draw.polyline().weight(3.0).points_colored(_model.my_line);
draw.to_frame(app, &frame).unwrap();
}
The compiler tells me something about wanting to move
out of my_line
but that it is not possible because the copy trait is not implemented.
error[E0507]: cannot move out of `_model.my_line` which is behind a shared reference
--> src/main.rs:30:48
|
30 | draw.polyline().weight(3.0).points_colored(_model.my_line);
| ^^^^^^^^^^^^^^ move occurs because `_model.my_line` has type `Vec<(Vec2, nannou::prelude::Hsl)>`, which does not implement the `Copy` trait
I am fairly new to rust and do not understand what is going on.
1 answer
Problem was my_line
is owned by _model
and cannot be moved.
Copying the entire my_line
is apparently not possible, but what worked is making an element-wise copy of my_line
, which is of type (Point2, Hsl)
.
Using iter()
to get an iterator and then copied()
to copy the items did work.
The code of the view()
function not looks like this:
fn view(app: &App, _model: &Model, frame: Frame) {
let draw = app.draw();
draw.background().color(GRAY);
draw.polyline().weight(3.0).points_colored(_model.my_line.iter().copied());
draw.to_frame(app, &frame).unwrap();
}
Thanks to dzil123
in the nannou matrix chat for pointing this one out to me.
1 comment thread