Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are structs with round brackets in Rust for?

Tags:

rust

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?

like image 516
George Shuklin Avatar asked Apr 08 '18 10:04

George Shuklin


People also ask

What is struct rust?

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.

How do you make a struct mutable in Rust?

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 do you access struct members in Rust?

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.

How do you create objects in Rust?

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.


1 Answers

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);
like image 155
Januson Avatar answered Oct 13 '22 06:10

Januson