Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
URL Rewriter Bot
URL Rewriter Bot

Exactly in the same way than this questionquestion, I would like that the return type of a function to be a trait, the return value being an instance of a type implementing that trait. A simple example:

fn myfunction() -> Box<Printable> { box TypeB{val: 2} as Box<Printable> } 

If I don't explicitly cast into a box of my generic trait, I get:

error: mismatched types: expected Box<Printable> but found Box<TypeB> (expected trait Printable but found struct TypeB)

So I wonder:

  • If it is the normal way to proceed in Rust to return a trait type
  • Why the Rust compiler cannot infer that automatically downcast

Any idea? I am using the current nightly version of the compiler.

Exactly in the same way than this question, I would like that the return type of a function to be a trait, the return value being an instance of a type implementing that trait. A simple example:

fn myfunction() -> Box<Printable> { box TypeB{val: 2} as Box<Printable> } 

If I don't explicitly cast into a box of my generic trait, I get:

error: mismatched types: expected Box<Printable> but found Box<TypeB> (expected trait Printable but found struct TypeB)

So I wonder:

  • If it is the normal way to proceed in Rust to return a trait type
  • Why the Rust compiler cannot infer that automatically downcast

Any idea? I am using the current nightly version of the compiler.

Exactly in the same way than this question, I would like that the return type of a function to be a trait, the return value being an instance of a type implementing that trait. A simple example:

fn myfunction() -> Box<Printable> { box TypeB{val: 2} as Box<Printable> } 

If I don't explicitly cast into a box of my generic trait, I get:

error: mismatched types: expected Box<Printable> but found Box<TypeB> (expected trait Printable but found struct TypeB)

So I wonder:

  • If it is the normal way to proceed in Rust to return a trait type
  • Why the Rust compiler cannot infer that automatically downcast

Any idea? I am using the current nightly version of the compiler.

Source Link
Fabimaru
  • 493
  • 4
  • 11

Traits as a return value from a function, and explicit cast

Exactly in the same way than this question, I would like that the return type of a function to be a trait, the return value being an instance of a type implementing that trait. A simple example:

fn myfunction() -> Box<Printable> { box TypeB{val: 2} as Box<Printable> } 

If I don't explicitly cast into a box of my generic trait, I get:

error: mismatched types: expected Box<Printable> but found Box<TypeB> (expected trait Printable but found struct TypeB)

So I wonder:

  • If it is the normal way to proceed in Rust to return a trait type
  • Why the Rust compiler cannot infer that automatically downcast

Any idea? I am using the current nightly version of the compiler.