Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mention both static and dynamic dispatch in the introduction to traits. #376

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,19 @@ impl Greet for Cat {
}
}

// Generic function (more in the next chapter).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you try enabling the "aspect-ratio helper" preprocessor here: https://github.com/google/comprehensive-rust/blob/main/book.toml#L24. I think you'll quickly see that there is not enough space on the page for such a long code example.

fn greetings<T: Greet>(greetable: T) {
println!("Hello, what is your name?");
greetable.say_hello();
}

fn main() {
// Static (compile-time) dispatch.
greetings(Dog { name: String::from("Fido") });
greetings(Cat);
println!("----------");

// Dynamic (runtime) dispatch.
let pets: Vec<Box<dyn Greet>> = vec![
Box::new(Dog { name: String::from("Fido") }),
Box::new(Cat),
Expand All @@ -39,6 +51,8 @@ fn main() {
<details>

* Traits may specify pre-implemented (default) methods and methods that users are required to implement themselves. Methods with default implementations can rely on required methods.
* Traits can be used for both compile-time and runtime dispatch, respectively
via generics and dynamic objects
* Types that implement a given trait may be of different sizes. This makes it impossible to have things like `Vec<Greet>` in the example above.
* `dyn Greet` is a way to tell the compiler about a dynamically sized type that implements `Greet`.
* In the example, `pets` holds Fat Pointers to objects that implement `Greet`. The Fat Pointer consists of two components, a pointer to the actual object and a pointer to the virtual method table for the `Greet` implementation of that particular object.
Expand Down