Rust Scripting

This crate shows the need for scripting with rust ...

Actually it is very easy from my point of view:

// Add main function only at compile time and 
// in case if program was run as rustc net.rs and 
// there was no main function it self
fn main() {
    ... wrap any code that was in file
}

I do not understand why we cannot do as it was described in this comment

In case if the was detected main function a generated code will look like this:

fn main() {
  ... some top-level code
  fn custom_main() {
    ...
  }
  custom_main();
}

Original main function that is in file will be with different name custom_main

Even if it is easy to implement, it's a major change to the language whose only benefit is that it saves you 12 key strokes. I don't see how this could be justified as a language feature.

However, it's absolutely possible to implement this in the playground, or in one of the previously mentioned tools.

The playground already detects if the code contains a main function. I guess it could also provide a button to automatically wrap the code in a main function.

9 Likes

Rust items are not required to be in order, while statements are. It can be very confusing to have both of them in the same scope, and best practice would be to put statements inside a main function even if this were an option.

2 Likes

How to configure cargo-script to wrap everything in a fn main() ? I have not found in documentation ...

That was a suggested feature that has not been implemented:

The main reason is that script mode gives better readability in some cases: Instead of searching for main function, for scripting mode you will need to read file from top to bottom and it is much simpler and nicer as for me :wink:

This definitely sounds odd.

"Instead of just (finding and) reading fn main, you just read the whole file from top to bottom!"

It sounds like the latter is more work and more likely to cause missed code.

And again, I'd like to point at Python again, where it's best practice for any non-extremely-trivial script to nest all of its "executed as script" code under a if __name__ == "__main__" header, rather than strewn about the file.

Or, in other words, a fn main().

Top level statements for scripting makes the already easy case easier, and any moderate complexity a lot more potentially problematic.

7 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.