I'm trying to get more in the habit of programming by giving myself a directed task, and the one I found to create a toy layout engine seemed to be a good match. Since I'm focusing on learning Python, I figured it would be good practice to convert the tutorial into Python. I figured at the same time, this would teach me something about Rust, and about reading code in general. A win all around!
I'm having a difficult time understanding what the keywords (are they even keywords?) Some
and Simple
do. They show up in the code presented:
enum Selector {
Simple(SimpleSelector),
}
struct SimpleSelector {
tag_name: Option<String>,
id: Option<String>,
class: Vec<String>,
}
I gather that an enum is a way of storing data that may be (exactly) one of several possible types, but I don't see what this means here.
Another thing that shows up in the author's code is (for example)
match self.next_char() {
'#' => {
self.consume_char();
selector.id = Some(self.parse_identifier());
}
In this case, I have no idea what the term Some
does. I have tried looking through the official Rust documentation but I cannot find a description of these terms, even though Some
is used in the documentation!
What do these terms do? More generally is there a list of Rust keywords? No searching for "rust programming language keywords" seems to be helping.
Rust features Algebraic Data Types which in short are data types with several possible shapes, for example:
enum OptionInt {
None,
Some(i32),
}
Is a data type which is either None
(a singleton value) or Some(i32)
(an i32
). In this case, None
and Some
are data constructors: when applied to a value (or without any value in the case of None
) they produce a value of type OptionInt
.
Those data constructors will also appear in pattern-matching:
match an_option_int {
Some(an_integer) => 3 * an_integer,
None => 0
}
is an expression that will produce an i32
which is either:
0
if an_option_int
contained None
6
if an_option_int
contained Some(2)
This features is also known as tagged unions.
These are not keywords, they are giving names to the variants of the enum. Relevant section in the guide. The list of keywords is in the reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With