【1日目】Rust入門


【1日目】Rust入門

最終目標

実際にwebアプリに組み込んでみて、Web Assemblyの実力を感じてみる。

本日の目標

とりあえず公式通りにセットアップ、文法の理解は飛ばします。
https://www.rust-lang.org/ja/learn/get-started

環境

OS:Mac OS Catalina

まずはインストール

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

このインストールにかかる時間1時間45分って聞いてたんですけど
あれ、一瞬...

VS Codeのプラグイン

VsCodeにてrustと検索してRustっていうプラグインを入れました
機能一覧
code completion
jump to definition, peek definition, find all references, symbol search
types and documentation on hover
code formatting
refactoring (rename, deglob)
error squiggles and apply suggestions from errors
snippets
build tasks

 プロジェクトを作成

公式ページの通りセットアップしていきます

hello-rustというディレクトリ に「Hello, world!」プロジェクトを生成

cargo new hello-rust

書いてみる

cargo.tomlファイルに追記

[dependencies]
ferris-says = "0.2"

buildを実行する

cargo build

cargo.lockに

[[package]]
name = "ferris-says"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f34f82e9a8b1533c027d018abd90b8687bf923be287b2617dfce4bea4ea3687"
dependencies = [
 "clap",
 "error-chain",
 "smallvec",
 "textwrap",
 "unicode-width",
]

追加されていますね

main.rsに実際に書いていきいます。

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

fn main() {
    let stdout = stdout();
    let message = String::from("Hello fellow Rustaceans!");
    let width = message.chars().count();

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

最後にプロンプトで実行

cargo run

所々解説

mutについて

変数をミュータブルにするために使います

let num = 1;
num = 2 //error


let mut num = 1;
num = 2 //ok

&について

参照するって意味。

参考 この記事が分かりやすかったです。
https://qiita.com/cactaceae/items/2c70a9947364c60ec100

所感

ここまで、他の言語やnpmなどを使ってきた人なら考えることも無くすんなり理解できそうな内容で、思ってたより敷居は低くなってるのかなって感じです。

今後

裏で文法事項を学習しつつ、簡単なプログラム作成を目指します。