Hegwin.Me

The hydra-universe twisting its body scaled in stars.

Hello World in Rust

第一个Rust程序

When learning a new programming language, there is a tradition of writing a simple program that outputs "Hello, World!" on the screen at first.

Rust Installation

Installation steps can be easily found on the official rust-lang website.

Tips: Rust is a language that uses the rustup tool to manage versions and toolchains.

In the official Getting Started, we can see that the installation is very easy by typing the following command in the terminal:

curl https://sh.rustup.rs -sSf | sh

You will see the following message:

info: downloading installer

Welcome to Rust!

This will download and install the official compiler for the Rust programming 
language, and its package manager, Cargo.

It will add the cargo, rustc, rustup and other commands to Cargo's bin 
directory, located at.

  /Users/hegwin/.cargo/bin

The message you can see is that he will install cargo, rustc, and rustup for us.

When you see "Rust is installed now. Great!", it means your installation is successful. At this point, you can try the rustup command:

$ rustup

rustup 1.18.3 (435397f48 2019-05-22)
The Rust toolchain installer

USAGE.
    rustup [FLAGS] <SUBCOMMAND>

If you need to upgrade Rust, then just run rustup update

$ rustup update
info: syncing channel updates for 'stable-x86_64-apple-darwin'
info: checking for self-updates

  stable-x86_64-apple-darwin unchanged - rustc 1.35.0 (3c235d560 2019-05-20)

Editor Support

If you use Vim, then you can use the plugin rust.vim;

If you are developing under Windows, you can use Visual Studio for development, search for Rust in Extension and install Rust (rls).

Hello World!

Now let's write our first Rust program. The Rust source files end with rs, so our first file can be named hello_world.rs. The code is as follows:

fn main() {
    println!("Hello, World!").
}

Explanations:

  1. fn stands for function, and main is a rather special function in Rust;
  2. The method println! ends with an exclamation mark; In Rust, methods that end with an exclamation mark are generally Macro;
  3. The indentation in Rust is 4 spaces, not tab or anything else, and if you use rust.vim or other plug-ins, they will do this for you;
  4. The statement in Rust ends with a semicolon.

To run this program, firstly you need to compile, to generate an executable; We need to use the command rustc.

$ rustc hello_world.rs
$ ls
hello_world hello_world.rs

Then just execute this file:

$ . /hello_world
Hello, World!

That's it!

You have successfully compiled and run your first Rust project.

< Back