cannot return reference iwth incompatible origin

What's the easiest way to deal with this error?
No description
1 Reply
Manuel Saelices
Manuel SaelicesOP3mo ago
This is the whole code snippet:
@value
struct Shape:
var area: Float64


trait Drawable:
fn get_shapes(ref self) -> ref [self] List[Shape]:
...

@value
struct Canvas(Drawable):
var shapes: List[Shape]

fn get_shapes(ref self) -> ref [self] List[Shape]:
return self.shapes

fn total_area(self) -> Float64:
var total: Float64 = 0
for shape in self.shapes:
total += shape[].area
return total

fn main():
var canvas = Canvas(shapes=List[Shape]())

shapes = canvas.get_shapes()
shapes.append(Shape(area=10.5))
print(canvas.total_area())
@value
struct Shape:
var area: Float64


trait Drawable:
fn get_shapes(ref self) -> ref [self] List[Shape]:
...

@value
struct Canvas(Drawable):
var shapes: List[Shape]

fn get_shapes(ref self) -> ref [self] List[Shape]:
return self.shapes

fn total_area(self) -> Float64:
var total: Float64 = 0
for shape in self.shapes:
total += shape[].area
return total

fn main():
var canvas = Canvas(shapes=List[Shape]())

shapes = canvas.get_shapes()
shapes.append(Shape(area=10.5))
print(canvas.total_area())
As there is a Drawable trait that does not know the shapes attribute, we cannot just replace ref [self] with ref [self.shapes]

Did you find this page helpful?