Jerry Ajay
Jerry Ajay

Reputation: 1094

self behavior in Rust

I want to draw attention to the self keyword.

This code compiles fine:

let color_code = self.color_code;
self.buffer.chars[row][col].write(ScreenChar {
    ascii_character: byte,
    color_code,
});

With my knowledge of Java's this keyword, I'm urged to think of the self substitution wrongly as:

self.buffer.chars[row][col].write(ScreenChar {
    ascii_character: byte,
    self.color_code: self.color_code,
});

i.e. I've removed the let color_code and used self.color_code: self.color_code.

I'm curious as to why my intuition is wrong with regards to Rust.

Upvotes: 0

Views: 102

Answers (1)

phimuemue
phimuemue

Reputation: 36031

let color_code = self.color_code does not modify self.color_code. In this regard it is very different from Java's implied this..

What it does instead is creating a new scope-local variable color_code that is initialized with self.color_code.

When you create/initialize a struct (in your case ScreenChar), then rust expects you to initialize the members in a certain way. Excerpt here:

  • field: value: In this case, rust assumes field is the name of a member of the struct, but self.color_code is not the name of a member of ScreenChar (color_code is). Thus, you probably only want color_code: self.color_code.
  • field: In this case rust assumes field is the name of a member of the struct and also requires a variable of the same name in scope.

For more information, you can have a look at https://doc.rust-lang.org/book/ch05-01-defining-structs.html#defining-and-instantiating-structs.

Upvotes: 1

Related Questions