5

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.

Community
  • 1
  • 1
Fabimaru
  • 423
  • 3
  • 9

1 Answers1

2

Yes, a trait object like that is the correct way to return a trait, although, if possible, returning a concrete type without a Box is more flexible: the callers of that function can box/cast if they need to. If that isn't directly possible, defining and returning an enum may work. (Boxing and trait objects should be regarded as somewhat of a last resort: it is often less efficient than other strategies.)

Unfortunately, implicit coercions don't yet infer from return values (they do in other contexts e.g. foo(box bar) will coerce that argument to a trait object if required); this will hopefully be fixed, but the explicit cast is required for now.

huon
  • 94,605
  • 21
  • 231
  • 225
  • Thanks. The idea of my test was to write a factory function (ex: implementing an abstraction layer to a DB). – Fabimaru Jul 06 '14 at 10:33
  • @Fabimaru, ah, that does sound something trait objects may be appropriate for. – huon Jul 06 '14 at 11:19