Is it possible to declare local anonymous structures in Rust?

Sometimes I like to group related variables into functions without declaring a new type of structure.

In C, this can be done, for example:

void my_function() {    
    struct {
        int x, y;
        size_t size;
    } foo = {1, 1, 0};
    // ....
}

Is there any way to do this in Rust? If not, what will be the closest equivalent?

+4
source share
1 answer

Although anonymous structures are not supported, you can localize them to do almost as described in version C:

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

Another option is a tuple:

fn main() {

    let obj = (1, 0, 1);

    println!("{}", obj.0);
    println!("{}", obj.1);
    println!("{}", obj.2);
}

Playground

+8
source

Source: https://habr.com/ru/post/1651626/


All Articles