Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top