Sometimes I like to group related variables in a function, without declaring a new struct type.
In C this can be done, e.g.:
void my_function() { struct { int x, y; size_t size; } foo = {1, 1, 0}; // .... }
Is there a way to do this in Rust? If not, what would be the closest equivalent?
To define a struct, we enter the keyword struct and name the entire struct. A struct's name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call fields.
An anonymous struct declaration is a declaration that declares neither a tag for the struct, nor an object or typedef name. Anonymous structs are not allowed in C++. The -features=extensions option allows the use of an anonymous struct declaration, but only as member of a union.
Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using example_struct. field syntax.
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.
While anonymous structs aren't supported, you can scope them locally, to do almost exactly as you've described in the C version:
fn main() { struct Example<'a> { name: &'a str }; let obj = Example { name: "Simon" }; let obj2 = Example { name: "ideasman42" }; println!("{}", obj.name); // Simon println!("{}", obj2.name); // ideasman42 }
Playground link
One other option is a tuple:
fn main() { let obj = (1, 0, 1); println!("{}", obj.0); println!("{}", obj.1); println!("{}", obj.2); }
Playground link
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