Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.



If 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 :-)




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: