If I get it right, calls to traits are resolved in runtime (so, traits are
kind of similar to C++ virtual methods).

What I'm proposing here is a compile-time approach.

Let's say we have the following trait:

pub trait LCD {
  fn line(&mut self, x0_b: i32, y0_b: i32, x1: i32, y1: i32, color: u8);
  fn rect(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: u8);
  fn fillrect(&mut self, x0_b: i32, y0_b: i32, x1_b: i32, y1_b: i32, color:
u8);
  fn putc(&mut self, value: char);
  fn puts(&mut self, s: &str);

  fn flush(&self);
  fn clear(&mut self);
}

which defined a LED screen. There are two structs implementing it: C12832
and ILI9341 (two different lcd controllers).

So I want my app to print hello world on lcd, I write the following code:

  let mut lcd = lcd_c12832::C12832::new(spi);
  let mut l: &mut lcd::LCD = lcd as &mut lcd::LCD;
  l.puts("hello, world");

Which results in a runtime dispatch, a slower and bigger code than the one
I'd have without a trait.

A second problem is there is no easy way to write unified code that
supports both the lcds based on passed in --cfg, as I can't
apply #[cfg(lcd_c12832)] to a chunk of code in fn, and it's kind of
problematic to return a &LCD out from it given that there is no heap and no
analog of placement new from C++.

Proposed binding concept solves those two problems:

#[cfg(lcd_c12832)]
let Binding: binding {
  let lcd: &lcd_c12832::C12832;
  let main: &Main;

  bind main.lcd = lcd;
}

at this point of time compiler can be sure about what struct is
implementing LCD trait for main.lcd and can bind the function bodies as
compile time, inlining them if applicable.

This also might be something that is already implemented, please advice.
The goal here is to minimise runtime code being executed and its size.


On Mon, Mar 31, 2014 at 3:06 PM, Daniel Micay <danielmi...@gmail.com> wrote:

> I'm not really sure exactly what it being proposed here.
>
> Rust's generic types and functions are already entirely expanded at
> compile-time. You *can* use traits as objects for dynamic dispatch, but
> it's not how they're used in the vast majority of cases.
>
>


-- 
Sincerely,
Vladimir "Farcaller" Pouzanov
http://farcaller.net/
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to