Where to place tuple struct correctly?


#1

Hi. Where to place this tuple struct correctly? Outside the boundaries of the main function or inside it?

struct Color(u32, u32, u32);

fn main() {
    // some code
}

or

fn main() {
    struct Color(u32, u32, u32);
    
    // some code
}

#2

Inside the main, if you can. As a general rule define names in the smallest namespace that allows your code to compile :slight_smile:


#3

It depends on the rest of the project. If you begin to have a lot of functions manipulating this Color struct, you might put this code into its own module. Otherwise leonardo is right :slight_smile:


#4

I’d say it’s a matter of taste and subjective opinion of what’s readable. I define all structs outside functions.


#5

In general I agree with @kornel that the module boundary is sufficient, and default to putting structs outside of functions.

The only exception that comes to mind is super-specific types used as minor implementation details, maybe if I needed something like

#[repr(align(16))]
struct Buffer([u8; 64]);

#6

As a concrete example of what @scottmcm mentioned, I recalled seeing https://github.com/rayon-rs/rayon/blob/master/rayon-core/src/registry.rs#L255 in rayon code.


#7

Couple of days ago @nrc asked on twitter about community’s “aha!” moments when learning Rust (really, check the thread out!) And here comes my third one: one may define structs and even impls inside fns. :open_mouth:


#8

Even inside blocks inside function calls inside functions!

Which is actually really useful – if you use the eval bot on IRC it just puts whatever you typed

fn main() {
    println!("{:?}", {
        in_here()
    });
}