Could someone please tell me why there is an asterisk here?

Hi all, I'm a complete newbie and I'm doing some rust practice and I successfully completed this exercise without an asterisk but when I look at the solution is has one and I'm not sure why it would be there.

The line is here in this solution (match *self):

impl TrafficLightColor {
    fn color(&self) -> String {
        match *self {
            TrafficLightColor::Red => "red".to_string(),
            TrafficLightColor::Yellow => "yellow".to_string(),
            TrafficLightColor::Green => "green".to_string(),
        }
    }
}

Thanks!

That * is the dereferencing operator. On the type level it turns a dereferencable type such as Box<T> or &mut T or &T into the respective target type (T in that case). As for implementation, the story is a bit more complicated, since an expression like your *self example does not inherently do a sort of "read" operation producing a value (in this case of type TrafficLightColor) but instead refers to the "place" of the original value; so e.g. a match expression like this does not actually need to consume (take ownership) of such a value in order to determine the right case, so it even works for non-Copy types.

As for why either of *self or self works: thats a feature called "match ergonomics" (some people don't really like this feature because it can be a bit confusing and complex). The sort-of "more proper" way to write this code would indeed be to use *self or to match self against patterns like &TrafficLightColor::Red (note the ampersand at the beginning). To read more about this, I've just looked up some good-looking beginner-friendly material for you and found that this post has a short intro section for match ergonomics, too. And also this post is often recommended to read.

6 Likes

Hi Steffahn,

Thank you for this most amazing reply.

Following your reply and the match ergonomics link I can understand what is happening now, it's automatically dereferencing and inserting the ref as it's the "only sensible thing to do" (as mentioned in the link). Which explains why both syntax's are successful, essentially they're doing the same thing.

Really appreciate the help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.