SDL2 I cannot use draw_points and draw_lines functions

Hello.
I'm new in the forum, I'm learning rust and sdl library, and it's pretty cool but difficult too, for a lot of reasons. One of these is the difficulty to find tutorials about sdl with rust, then I have to read sdl-C tutorials for the theory and rust technical doc here like a professional geek: sdl2 - Rust

So my question concerns the 2 functions in title, impossible for me compile with them:

// I want to draw an triangle
    let mut points_tableau: [Point; 3] = [Point::new(0, 0); 3];
    points_tab[1].x = 100;
    points_tab[2].y = 50;
    canvas.draw_lines(points_tableau);

// I want to draw a circle
const PI: f32 = 3.14159265358979323846264338327950288;
let mut points: [Point; 100] = [Point::new(0, 0); 100];
let nb_points = 100;
let rayon = 200f32;
for i in 0..nb_points
{
	let mut point_flottant = 0.0;
	let mut angle: f32 = 2.0 * PI * i as f32 / nb_points as f32; 

	point_flottant = angle.cos() * rayon + 200.0;
	points[i].x = point_flottant.round() as i32;

	point_flottant = angle.sin() * rayon + 200.0;
	points[i].y = point_flottant.round() as i32;
}
canvas.draw_points(points);

Google is not my friend this time, nor the doc:

pub fn draw_points<'a, P: Into<&'a [Point]>>(&mut self, points: P) -> Result<(), String>

You can see in my examples that I created an array with "Point" inside, I did exactly the same in C and it worked. I don't know what to do.

...nor the compiler:

error[E0277]: the trait bound `&[sdl2::rect::Point]: std::convert::From<[sdl2::rect::Point; 100]>` is not satisfied
  --> src/main.rs:38:16
   |
38 |         canvas.draw_points(points);
   |                ^^^^^^^^^^^ the trait `std::convert::From<[sdl2::rect::Point; 100]>` is not implemented for `&[sdl2::rect::Point]`
   |
   = help: the following implementations were found:
             <[sdl2::sdl2_sys::SDL_MessageBoxColor; 5] as std::convert::From<sdl2::messagebox::MessageBoxColorScheme>>
   = note: `std::convert::From<[sdl2::rect::Point; 100]>` is implemented for `&mut [sdl2::rect::Point]`, but not for `&[sdl2::rect::Point]`
   = note: required because of the requirements on the impl of `std::convert::Into<&[sdl2::rect::Point]>` for `[sdl2::rect::Point; 100]`

Thank you very much for your help. It's frustrating to stay blocked on basis.

Paul

1 Like

You need to pass in a reference to a slice to draw points.

// &point[..] converts an array into a reference to a slice
// this is (ab)using the fact that indexing an array with ranges gives a slice
canvas.draw_points(&points[..]);

You can do something similar with draw_lines

That function signature is obscene. It should be using AsRef or better yet, just take a slice directly. Into is just wrong there.

2 Likes

Hey it works, thank you!!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.