I found a language construct I don't understand:
pub struct OpenOptions(fs_imp::OpenOptions);
I even created a compilable piece of code with those brackets but I still couldn't understand it:
struct Foo {
bar: i32,
}
struct Baz(Foo);
fn main() {
let mut x: Baz = Baz(Foo{ bar: 3 });
}
What are those round brackets for?
Keyword structA type that is composed of other types. Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs.
To create an instance of this struct, we use the struct expression and assign it to a mutable variable. A mutable variable uses the mut keyword between the let keyword and the variable name. }; At this point, we have an instance whose content we can modify anywhere in the same code block.
How to access struct properties (members) We access struct properties with dot notation. That means we separate the struct's variable name and its property name with the dot operator. In the example above, we print the properties from each struct by accessing their values with dot notation.
In rust we do not create objects itself, we call them instances. To create a instance you just use the struct name and a pair of {}, inside you put the name of the fields with values.
As pointed out in the comments, those are Tuple Structs. They are useful when you want to distinguish one tuple from others, but naming each of its fields would be redundant or needlessly verbose. In other words you clarify the purpose of a tuple by naming it.
Tuple structs can be used to create a simple value objects.
struct Color(i32, i32, i32);
let black = Color(0, 0, 0);
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