Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute Rust code directly on Unix systems? (using the shebang)

Tags:

shebang

rust

From reading this thread, it looks like its possible to use the shebang to run Rust *.

#!/usr/bin/env rustc

fn main() {
    println!("Hello World!");
}

Making this executable and running does compile, but not run the code.

chmod +x hello_world.rs
./hello_world.rs

However this only compiles the code into hello_world.

Can *.rs files be executed directly, similar to a shell script?


* This references rustx, I looked into this, but its a bash script which compiles the script every time (without caching) and never removes the file from the temp directory, although this could be improved. Also it has the significant limitation that it can't use crates.

like image 897
ideasman42 Avatar asked Dec 25 '16 15:12

ideasman42


People also ask

Does Rust compile to binary?

After compiling successfully, Rust outputs a binary executable. On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the ls command in your shell.


2 Answers

There's cargo-script. That also lets you use dependencies.

After installing cargo-script via cargo install cargo-script, you can create your script file (hello.rs) like this:

#!/usr/bin/env run-cargo-script

fn main() {
    println!("Hello World!");
}

To execute it, you need to:

$ chmod +x hello.rs
$ ./hello.rs
   Compiling hello v0.1.0 (file://~/.cargo/.cargo/script-cache/file-hello-d746fc676c0590b)
    Finished release [optimized] target(s) in 0.80 secs
Hello World!

To use crates from crates.io, please see the tutorial in the README linked above.

like image 87
DK. Avatar answered Oct 15 '22 06:10

DK.


This seems to work:

#!/bin/sh
//usr/bin/env rustc $0 -o a.out && ./a.out && rm ./a.out ; exit

fn main() {
    println!("Hello World!");
}
like image 5
wimh Avatar answered Oct 15 '22 06:10

wimh