Rust - Getting Started

Installing Rust on MacOs

Rustup: the Rust installer and version management tool.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Project and Package Manage

Cargo: the Rust build tool and package manager.
Like Maven for Java.

  • build your project with cargo build
  • run your project with cargo run
  • test your project with cargo test
  • build documentation for your project with cargo doc
  • publish a library to crates.io with cargo publish

Hello Rust

Use cargo to create a project very easily.

$ cargo new hello-rust

This will generate a new directory called hello-rust with the following files:

hello-rust
|- Cargo.toml
|- src
  |- main.rs

Cargo.toml is the manifest file for Rust. It’s just like pom.xml for Maven project.
src/main.rs is where we’ll write our application code.

Run this cargo project by using following command:

$ cargo run
   Compiling hello-rust v0.1.0 (/Users/ag_dubs/rust/hello-rust)
    Finished dev [unoptimized + debuginfo] target(s) in 1.34s
     Running `target/debug/hello-rust`
Hello, world!

A simple application with dependency

In this project, we’ll use a crate called ferris-says.

In our Cargo.toml file we’ll add this information (that we got from the crate page):

[dependencies]
ferris-says = "0.1"

Now let’s write a small application with our new dependency. In our main.rs, add the following code:

use ferris_says::say; // from the previous step
use std::io::{stdout, BufWriter};

fn main() {
    let stdout = stdout();
    let out = b"Hello fellow Rustaceans!";
    let width = 24;

    let mut writer = BufWriter::new(stdout.lock());
    say(out, width, &mut writer).unwrap();
}

Then run the application:

$ cargo run

The output is:

----------------------------
| Hello fellow Rustaceans! |
----------------------------
              \
               \
                 _~^~^~_
             \) /  o o  \ (/
               '_   -   _'
               / '-----' \
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值