misc/process/wait.html)
    9. [ **20.6.** Filesystem Operations ](../std_misc/fs.html)
    10. [ **20.7.** Program arguments ](../std_misc/arg.html) â± 
    11.       1. [ **20.7.1.** Argument parsing ](../std_misc/arg/matching.html)
    12. [ **20.8.** Foreign Function Interface ](../std_misc/ffi.html)
  41. [ **21.** Testing ](../testing.html) â± 
  42.     1. [ **21.1.** Unit testing ](../testing/unit_testing.html)
    2. [ **21.2.** Documentation testing ](../testing/doc_testing.html)
    3. [ **21.3.** Integration testing ](../testing/integration_testing.html)
    4. [ **21.4.** Dev-dependencies ](../testing/dev_dependencies.html)
  43. [ **22.** Unsafe Operations ](../unsafe.html) â± 
  44.     1. [ **22.1.** Inline assembly ](../unsafe/asm.html)
  45. [ **23.** Compatibility ](../compatibility.html) â± 
  46.     1. [ **23.1.** Raw identifiers ](../compatibility/raw_identifiers.html)
  47. [ **24.** Meta ](../meta.html) â± 
  48.     1. [ **24.1.** Documentation ](../meta/doc.html)
    2. [ **24.2.** Playground ](../meta/playground.html)

__ __

  * Light (default) 
  * Rust 
  * Coal 
  * Navy 
  * Ayu 

__

#  Rust By Example

[ __ ](../print.html "Print this book") [ __ ](https://github.com/rust-
lang/rust-by-example "Git repository") [ __ ](https://github.com/rust-
lang/rust-by-example/edit/master/src/trait/dyn.md "Suggest an edit")

#  Returning Traits with ` dyn `

The Rust compiler needs to know how much space every function's return type
requires. This means all your functions have to return a concrete type. Unlike
other languages, if you have a trait like ` Animal ` , you can't write a
function that returns ` Animal ` , because its different implementations will
need different amounts of memory.

However, there's an easy workaround. Instead of returning a trait object
directly, our functions return a ` Box ` which _contains_ some ` Animal ` . A
` box ` is just a reference to some memory in the heap. Because a reference
has a statically-known size, and the compiler can guarantee it points to a
heap-allocated ` Animal ` , we can return a trait from our function!

Rust tries to be as explicit as possible whenever it allocates memory on the
heap. So if your function returns a pointer-to-trait-on-heap in this way, you
need to write the return type with the ` dyn ` keyword, e.g. ` Box<dyn Animal>
` .

    
    
    struct Sheep {}
    struct Cow {}
    
    trait Animal {
        // Instance method signature
        fn noise(&self) -> &'static str;
    }
    
    // Implement the `Animal` trait for `Sheep`.
    impl Animal for Sheep {
        fn noise(&self) -> &'static str {
            "baaaaah!"
        }
    }
    
    // Implement the `Animal` trait for `Cow`.
    impl Animal for Cow {
        fn noise(&self) -> &'static str {
            "moooooo!"
        }
    }
    
    // Returns some struct that implements Animal, but we don't know which one at compile time.
    fn random_animal(random_number: f64) -> Box<dyn Animal> {
        if random_number < 0.5 {
            Box::new(Sheep {})
        } else {
            Box::new(Cow {})
        }
    }
    
    fn main() {
        let random_number = 0.234;
        let animal = random_animal(random_number);
        println!("You've randomly chosen an animal, and it says {}", animal.noise());
    }
    
    

[ __ ](../trait/derive.html "Previous chapter") [ __ ](../trait/ops.html "Next
chapter")

[ __ ](../trait/derive.html "Previous chapter") [ __ ](../trait/ops.html "Next
chapter")