Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I borrow a pointer to a shared trait in Rust?

From the tutorial on borrowed pointers (broken), a bit modified:

struct Point {x: float, y: float}

fn compute(p1 : &Point) {}

fn main() {
    let shared_box : @Point = @Point {x: 5.0, y: 1.0};
    compute(shared_box);
}

And all is fine, because the shared box is automatically borrowed for the function.

But doing the same with a trait:

struct Point {x: float, y: float}
trait TPoint {}

impl TPoint for Point {}

fn compute(p1 : &TPoint) {}

fn main() {
    let shared_box : @TPoint = @Point {x: 5.0, y: 1.0} as @TPoint;

    compute(shared_box);
    //      ^~~~~~~ The error is here
}

And it fails, (compiler version 0.6) saying:

error: mismatched types: expected &TPoint but found @TPoint (trait storage differs: expected & but found @)

Is this a bug in the compiler? Or are borrowed pointers not allowed for traits?

If the answer is the latter, why is that?

like image 747
rodrigo Avatar asked May 02 '13 19:05

rodrigo


1 Answers

This is a known bug in the current version of Rust:

#3794: Casting to a trait doesn't auto-coerce to a &T type

There has been some work on trying to address this problem, but there are some technical details that need to be ironed out; interested parties can see some of the discussion (from a few months ago) here on pull request 4178.

like image 160
pnkfelix Avatar answered Sep 24 '22 06:09

pnkfelix