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

What is a trait object, exactly? #392

Open
ksqsf opened this issue Aug 7, 2018 · 3 comments
Open

What is a trait object, exactly? #392

ksqsf opened this issue Aug 7, 2018 · 3 comments

Comments

@ksqsf
Copy link

ksqsf commented Aug 7, 2018

The current wording is pretty confusing and needs refining.

A trait object is an opaque value of another type that implements a set of traits

This suggests a trait object is a value.

For example, given a trait Trait, the following are all trait objects:

  • Trait
  • dyn Trait
  • ...

This suggests "dyn Trait" itself is a trait object.

Syntax TraitObjectType : dyn? TypeParamBounds

This suggests a trait object is a value of type "dyn Trait".

After reading this section, I still don't know which part in

// rfc1909. not exactly sure this is correct.
let reader: dyn Read = File::open(path)?;

is the trait object here. Is it reader, dyn Read, or File?

@Havvy
Copy link
Contributor

Havvy commented Aug 12, 2018

reader is a variable that holds the trait object. dyn Read is the type of the trait object. File is what the trait object points to. And then the trait object itself is (currently implemented as) a struct that is a pointer to the File struct and a vTable for the Read methods and the size and alignment of the File type.

Though you'd have to do Box::new(File::open(path)? as dyn Read) or some other type that can hold a trait object because they are dynamically sized types so variables cannot hold them directly.

@mzji
Copy link

mzji commented Sep 14, 2018

I've found some comfusing definitions about trait object in different parts of Rust document.
In the document of standard library, &dyn Trait is trait object:
k46u yhx4 lc_3 s 8xejo
But in the Rust Reference, dyn Trait is trait object:
23h va0 5tgf b8vdfgraex
The definition of trait object is just a mess, we need to fix it.

@alercah
Copy link
Contributor

alercah commented Apr 16, 2020

Also, the non-auto (principal) trait no longer needs to come first, so this page is out of date, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants