Reputation: 8855
I want to access an object as read-only after it has been passed to another object which changes its state. I know there is a problem with accessing an object when its still under control by being borrowed.
extern crate renderay_rs;
use renderay_rs::*;
fn draw_canvas(canvas: &Canvas) {
let max_height = canvas.height;
let max_width = canvas.width;
for iterator_y in 0..max_height {
for iterator_x in 0..max_width {
print!("{}", canvas.array[iterator_y * iterator_x]);
}
print!("\n");
}
}
fn main() {
let point = Point { x: 5, y: 5 };
let mut canvas = Canvas {
width: 10,
height: 10,
array: vec!['o'; 10*10],
};
let mut renderer = CanvasRenderer::new(&mut canvas);
renderer.render_point('A', point);
draw_canvas(canvas);
}
I feel I should end the borrowing after the renderer.render_point(..., ...)
method. Is there a way to do so? The object has no need to be borrowed by it or the CanvasRenderer
after its state has been changed.
I've used block scope before, but I don't feel happy with this approach. I hope you can give me a hint for a better alternative!
Upvotes: 0
Views: 105
Reputation: 30061
You can introduce a block to reduce the scope of renderer
:
fn main() {
let point = Point { x: 5, y: 5 };
let mut canvas = Canvas {
width: 10,
height: 10,
array: vec!['o'; 10*10],
};
{
let mut renderer = CanvasRenderer::new(&mut canvas);
renderer.render_point('A', point);
}
draw_canvas(canvas);
}
Another way if you don't like blocks is to use functions. Rust will be able to figure out where the borrow ends from the lifetimes (here the function does not return anything, so the borrow ends after the function call):
fn render_things(canvas: &mut Canvas) {
let mut renderer = CanvasRenderer::new(canvas);
renderer.render_point('A', point);
}
fn main() {
let point = Point { x: 5, y: 5 };
let mut canvas = Canvas {
width: 10,
height: 10,
array: vec!['o'; 10*10],
};
render_things(&mut canvas);
draw_canvas(canvas);
}
Upvotes: 5