Use statements inside functions

So I always implement use statements for just the function that needs it. So heres my doubt:

Using use inside scopes limit memory alloc for that scope or compiler link all and dont care about functions scopes?

Is it usefull to use "use" statements on function scope or makes no diff?

like...

mod test { 
       fn foo() {
          use xxx;
          //do something with it.
        }

        fn bar( ) {
           use yyy;
           //do something with it.
        }
}

besides...

mod test { 
         use {xxx, yyy};

        fn foo() {
              //do something with it.
        }

        fn bar( ) {
           //do something 
       }
}

Please read Forum Code Formatting and Syntax Highlighting and edit the above post.

Sorry, fixed.

It makes no difference for the performance of the compiler if that's what you're thinking? It can sometimes be useful if you want something to only be in scope for a short time, but is quite rare.

1 Like

I'm not seeking for compiler time, seeking for resource alocation under heavy functions, on runtime call of the function, it will alocate only when its called or..?

Use statements are removed, and all paths are made absolute somewhat early in the compiler. Where you put your use statements has no effect the resulting executable.

2 Likes

use statements are just a binding between modules. The code in the function body is the only thing that can be "heavy" at runtime.

As stated above, use has no impact on any runtime characteristics, and is purely an instruction to the compiler on how to match up names and items.

Smaller scopes for uses are typically used for types you don't want in a larger scope, typically because they provide functionality that you don't want to accidentally use elsewhere, or they conflict with other names in scope. A common case is for glob importing of enum variants; this is typically discouraged at module scope because it pollutes the namespace, but it can be quite useful in functions that require special behavior for a large number of variants.

It's worth noting, however, that "statement level" use may have weaker IDE support than "module level" use; rust-analyzer doesn't even attempt name resolution for uses not at module scope.

4 Likes

I'll add one more reason for statement level use, which is for a rarely used item so that the reader doesn't have to scroll to the top of the file to know what it means.

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.