Rust Script

I just took rust-script for a spin. Fun!

It was really easy.

❯ cargo install rust-script

❯ rust-script -e '1+2'
3

The first thing I noticed is that we can jettison fn main! In From Perl to Rust, I mentioned that we don't have an explicit main in Perl, like we do in Rust. Well, we don't need it in rust-script either. We often struggle trying to define a scripting language. Perhaps that's the key right there. A scripting language is a programming language that doesn't require an explicit main.

For example, this Perl script

#!/usr/bin/env perl

use v5.40;

my $name = shift // 'World';

say "Hello, $name!";

looks almost identical in rust-script

#!/usr/bin/env rust-script

let name = std::env::args().nth(1).unwrap_or("World".into());

println!("Hello, {name}!");

Both behave identically.

❯ ./hello
Hello, World!

❯ ./hello Tim
Hello, Tim!

We can even make adjustments to our Cargo.toml file to use external crates and whatnot! However, then it seems we do need a main function. Here's a little script I wrote to decode QR codes with bardecoder.

#!/usr/bin/env rust-script
//! ```cargo
//! [dependencies]
//! bardecoder = "0.5"
//! image = "0.24"
//! ```
fn main() {
    let filename = std::env::args().nth(1).expect("Usage: bardecoder filename");
    let img = image::open(filename).expect("Cannot open image file");
    for result in bardecoder::default_decoder().decode(&img) {
        println!("{}", result.unwrap());
    }
}

Give it an image file with a QR code and it tells us what it says.

❯ qrencode -o rust-script.png https://rust-script.org/

❯ ./bardecoder rust-script.png 
https://rust-script.org/

Keen!