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?

1 Answer

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

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.