Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare local anonymous structs in Rust?

Tags:

struct

rust

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?

like image 618
ideasman42 Avatar asked Aug 18 '16 02:08

ideasman42


People also ask

How do you declare a struct in Rust?

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.

What is struct anonymous?

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.

Does rust have structs?

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.

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

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

like image 168
Simon Whitehead Avatar answered Oct 21 '22 05:10

Simon Whitehead