Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active July 5, 2021 14:45
Show Gist options
  • Save rpivo/2a40964f2960c9a1bd491391d9e4be8d to your computer and use it in GitHub Desktop.
Save rpivo/2a40964f2960c9a1bd491391d9e4be8d to your computer and use it in GitHub Desktop.
Using the Main Function in Rust

Using the Main Function in Rust

Some code from Steve Donogan's "Object Orientation in Rust" was used for this gist.

In Rust, the main() function will automatically be run.

fn main() {
    println!("Hello, world!");
}

// Hello, world!

If there is no main() function, the compiler will print a warning.

println!("Hello, world!");

/*
No main function was detected, so your code was compiled
but not run. If you’d like to execute your code, please
add a main function.
*/

It's fine to have other blocks of code declared before the main() function in the same file, even if those blocks of code aren't used within main().

trait Show {
    fn show(&self) -> String;
}

impl Show for i32 {
    fn show(&self) -> String {
        format!("four-byte signed {}", self)
    }
}

impl Show for f64 {
    fn show(&self) -> String {
        format!("eight-byte float {}", self)
    }
}

fn main() {
    println!("Hello, world!");
}

// Hello, world!

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment