Skip to content

Trait object coercion to borrowed trait does not work with methods on &self #9950

Closed
@Kimundi

Description

@Kimundi

This might not be a bug, but while writing extension traits for a trait object I discovered that calling a &self method of a trait implemented on a &Trait does not work if it needs to borrow from a ~Trait or @Trait first. This complicates things, because you need to explicit borrow to a &Trait prior to making the call.

As comparison, these three combinations work:

trait Bar{} 
impl Bar for uint {} 

// self by value
trait Foo { fn baz(self); }  
impl<'self> Foo for &'self Bar { fn baz(self) { println("baz"); } }; 

// borrowed trait object
let x = &5u as &Bar; 

x.baz();
> baz
trait Bar{}
impl Bar for uint {}

// self by value
trait Foo {fn baz(self);}
impl<'self> Foo for &'self Bar { fn baz(self) { println("baz"); } };

// owned trait object
let x = ~5u as ~Bar; 

x.baz();
> baz
trait Bar{}
impl Bar for uint {}

// self by reference
trait Foo {fn baz(&self);} 
impl<'self> Foo for &'self Bar { fn baz(&self) { println("baz"); } };

// borrowed trait object
let x = &5u as &Bar; 

x.baz();
> baz

While this one fails to compile:

trait Bar{}
impl Bar for uint {} 

// self by reference
trait Foo {fn baz(&self);} 
impl<'self> Foo for &'self Bar { fn baz(&self) { println("baz"); } };

// owned trait object
let x = ~5u as ~Bar; 

x.baz();
> error: type `~main::Bar:Send` does not implement any method in scope named `baz`

And this one is the workaround necessary to make it work:

trait Bar{}
impl Bar for uint {} 

// self by reference
trait Foo {fn baz(&self);} 
impl<'self> Foo for &'self Bar { fn baz(&self) { println("baz"); } };

// owned trait object
let x = ~5u as ~Bar; 

{let tmp: &Bar = x; tmp}.baz();
> baz

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-DSTsArea: Dynamically-sized types (DSTs)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions