3 ms·
This is very good but... Description of traits suddenly dumps references, mutable references, reference bindings, dereferencing with zero explanation: --- star
by dmitriid 7y ago
This is very good but... Description of traits suddenly dumps references, mutable references, reference bindings, dereferencing with zero explanation:
--- start quote ---
Trait methods can also take self by reference or mutable reference:
impl std::clone::Clone for Number {
fn clone(&self) -> Self {
Self { ..*self }
}
}
--- end quote ---
What? What does this even mean? What is <asterisk>self, and why?
Too many questions, not nearly enough answers.
- dilap 7y agoIf you have a struct of type T and an instance of that struct t, you can create a new instance using the syntax T { ..t } which means "a new T with all the fields set to their values in t". Inside the trait "Self" is an alias for "Number". "&self" is shorthand for "self: &Number", i.e., a reference to Number. To dereference a reference, prefix with * So: self has type "&Number" and *self has type "Number". Thus, Self { ..*self } is creating a new instance of Number with its each set to the same value as self. Disclaimer! everything I know about rust I learned 2 days ago from this blog post, so I might be wrong :-)