Cfg's in function signatures

Today I played and found you can use cfg in function signatures.


fn main() {
    #[cfg(not(feature = "use_generic"))]
    confuged(42);
    #[cfg(feature = "use_generic")]
    confuged("fourty two");
}

fn confuged<#[cfg(feature = "use_generic")] T: Display>(
    #[cfg(not(feature = "use_generic"))] var: u32,
    #[cfg(feature = "use_generic")] var: T,
) {
    println!("{}", var);
}

But not in the return part...

fn confuged<#[cfg(feature = "use_generic")] T: Display>(
    #[cfg(not(feature = "use_generic"))] var: u32,
    #[cfg(feature = "use_generic")] var: T,
) #[cfg(not(feature = "use_generic"))] ->  ()
13 | ) #[cfg(not(feature = "use_generic"))] ->  ()
   |   ^ expected one of `->`, `;`, `where`, or `{`

Part of my brain says "Do not do that". Impossible to read. But then I discovered you can also put comments and blank lines in the function signature and I wonder if I could make a small program just using cfg's in a function signature. is the combination of "all", "any", "not", and "cfg_attr" turing complete?
But of course reality and my day job might prevent that.

Arbitrary combinations of these are, in theory – you can make a NAND gate from not and all, and NAND gates are compute universal. That said, I don't know how much nesting is actually allowed by the syntax/spec/implementation.

I don't understand how that relates to cfg attributes, but of course you can – you can use comments and newlines pretty much anywhere any other kind of whitespace would be allowed. Breaking up a signature into multiple lines is useful when it grows longer than the line width of whatever style guidelines you follow (this can easily happen with 2-3 parameters and a generic return type, for instance).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.