🦀

RustのHello worldを書くので学習メモ

2021/07/04に公開

@armorik83 です。Rust Advent Calendar 2016も終盤ですが、ここへきて Hello world をやろうと思います。この記事を書き始めた段階で Rust 経験は 0 分なので、環境構築を進めながらリアルタイムに記事を書いていきます。

環境構築

Rust はコンパイルが必要な言語なので、まずはコンパイラ周りから準備します。『multirust が非推奨になったようなので rustup に移行する』という記事があったので、rustupを入れます。

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

ここは 1 を選択します。これでdownloading component 'rustc'が表示され、コンパイラのインストールが始まります。完了すると、なんかパスが通っていないので設定します。

.zshrc
export PATH="$HOME/.cargo/bin:$PATH"

これでパスが通ってrustccargoが触れるようになりました。cargoはパッケージマネージャだそうです。

$ rustc --version
rustc 1.13.0 (2c6933acc 2016-11-07)
$ cargo --version
cargo 0.13.0-nightly (eca9e15 2016-11-01)

Hello world

ソースを書いて動かしてみましょう。エディタはひとまず Atom でいきます。Atom にはlanguage-rustプラグインを入れました。

hello.rs
fn main() {
    println!("Hello World!");
}

とりあえず、公式からこのソースを持ってきて実行してみます。

$ rustc hello.rs

ここで Hello World!が出ると思ったら大間違い。コンパイルしただけなので、実行はされていません。バイナリが生成されているので、そちらを叩きます。

$ ./hello
Hello World!

できました!

ダブルクオートとシングルクオート

hello.rs
fn main() {
    println!("Hello World!");
}

Hello World!はダブルクオートで囲まれていますが、これはシングルクオートにするとどうなるのかやってみました。

$ rustc hello.rs
error: character literal may only contain one codepoint: ')
 --> hello.rs:2:27
  |
2 |     println!('Hello World!');
  |

怒られました。これは Rust ではシングルクオートはCharacter literals、ダブルクオートはString literals明確に区別されているからのようです

セミコロン

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

次に行末のセミコロンを消してみました。するとちゃんとコンパイルされ、動きます。この点について調べてみると、公式に言及がありました。

The line ends with a semicolon (;). Rust is an expression-oriented language, which means that most things are expressions, rather than statements. The ; indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a ;.

Rust は式指向の言語なので式の終わりには;を付けるということだそうです。慣れないうちは公式に従って付けておくほうがよさそうです。

いくつか試す

せっかくなので他の例を試します。

hello.rs
fn print_hello_world() {
    println!("Hello World!");
}

fn main() {
    print_hello_world();
}

関数呼び出し。これは他の言語となんら変わりないです。命名規則はどうやらスネークケース (snake_case) なので従っておきましょう。

次にクラスを作ろう…と思ったら Rust にはclassが無い?structimplで表現するっぽいです。

class Person {
  constructor(public name: string, public age: number) {}

  sayName() {
    console.log(`I'm ${this.name}, ${this.age} years old.`)
  }
}

const person = new Person('armorik', 83)
person.sayName()

この TypeScript のclassを Rust でそれっぽく書いてみます。

hello.rs
struct Person {
    name: String,
    age: i32,
}

impl Person {
    fn say_name(&self) {
        println!("I'm {}, {} years old.", self.name, self.age);
    }
}

fn main() {
    let person = Person {name: "armorik".to_string(), age: 83};
    person.say_name();
}

いくつか慣れが必要ですが。この辺りはまだなんとかなりそう。

最後に

1 時間もあれば環境構築していろいろ試せたので、興味ある人は年末年始にササッとやってみるといいと思います。

関連資料として、なぜかフロントエンドのカンファレンスで Rust の話をし続けていたこわいぱんだのスライドを置いておきます。それでは。

Discussion