Hmm, right. The as_* could probably useful to write a macro for.

Coming from the C/Java side of things I have to figure out how this works in a bigger context, e g a DList or other structure owning objects implementing HasArea. This seems to compile, e g:

impl Pancake {
    fn as_box_circle(&self) -> Box<Circle> { box self.circle }
}

fn make_pancake(dl: &mut DList<Box<HasArea>>) {
let p = Pancake { circle: Circle { x: 0f64, y: 0f64, radius: 1f64 }, is_tasty: true };
    dl.push(p.as_box_circle());
}

But I'd assume that make_pancake would now make a copy of the pancake's circle, rather than taking ownership of the entire pancake, right? The pancake then gets dropped at function return.

In this simple example perhaps this does not make that much of a difference though, but if you imagine a C struct like:

struct list {
   list *next;
   circle *data;
}

You can now put a pointer to a pancake as data, use it as a circle, and when you finally free the list and the data that goes with it, the entire pancake will be freed. This you cannot do in rust...or can you?


On 2014-10-17 07:59, Clark Gaebel wrote:
impl Pancake {
  fn as_circle(&self) -> &Circle { &self.circle }
  fn as_mut_circle(&mut self) -> &mut Circle { &mut self.circle }
}

The compiler will optimize trivial functions, except cross-crate. In those cases, use an #[inline] annotation.



On Thu, Oct 16, 2014 at 10:57 PM, David Henningsson <[email protected] <mailto:[email protected]>> wrote:

    This is probably a previously asked question, but I couldn't find
    it on
    Google, so...

    Let's extend the Circle example from the guide a little:

    struct Circle {
    x:f64,
    y:f64,
    radius:f64,
    }

    trait HasArea {
    fn area(&self)-> f64;
    }

    impl HasArea for Circle {
    fn area(&self)-> f64 {
    std::f64::consts::PI * (self.radius * self.radius)
    }
    }

    struct Pancake {
    circle: Circle,
    is_tasty: bool,
    }


    ...now, what is the easiest way I can implement HasArea for
    Pancake? I
    could do this:

    impl HasArea for Pancake {
    fn area(&self) -> f64 { self.circle.area() }
    }

    ...but that means a lot of boiler-plate code, especially if
    HasArea has
    many methods. Hopefully rust will just inline/optimise the
    redirection
    away in most cases to avoid the runtime cost, but is there a
    smarter or
    more idiomatic way of doing this?

    // David

    _______________________________________________
    Rust-dev mailing list
    [email protected]
    https://mail.mozilla.org/listinfo/rust-dev



_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to