追記 2018/02/25
brewで入れると色々横着なので、ちゃんとインストールし直した。
以下原文、読まなくていいです。
Rust、話題なので、やってみる。ミーハーなので。
brew install rust
% brew install rust % rustc -V rustc 1.16.0 % cargo -V cargo-0.17.0-dev (f9e5481 2017-03-03)
Hello, Rust!
% cd % mkdir -p proj/rust/playground/hello % cd proj/rust/playground/hello
fn main() { println("ハロー, Rust!"); }
% rustc hello.rs error[E0423]: expected function, found macro `println` --> hello.rs:2:5 | 2 | println("ハロー, Rust!"); | ^^^^^^^ did you mean `println!(...)`? error: aborting due to previous error %
めっちゃ親切やん
fn main() { - println("ハロー, Rust!"); + println!("ハロー, Rust!"); }
% rustc hello.rs % ./hello ハロー, Rust! %
できた
Write & Runがだるい
コンパイルして、実行ファイルを実行、っていう流れがだるいな、って思ったら、cargo run
というのがあるっぽい。本当はプロジェクトつくるときにcargo new
するのが作法のようで、cargo new
するとtests
も自動的につくってくれるっぽい。いいっぽい。今回は後からCargo.toml
を追加した。
FizzBuzz
こういう感じにしたい
% fizzbuzz 15 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 FizzBuzz!!!
こうなった
use std::env; fn fizzbuzz(x: i8) { for i in 1..(x + 1) { match (i % 3, i % 5) { (0, 0) => println!("FizzBuzz!!!"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), _ => println!("{}", i), } } } fn main() { match env::args().last().unwrap().parse::<i8>() { Ok(x) => fizzbuzz(x), Err(err) => println!("数字を指定してください: {}", err), } }
結果
% cargo run 18 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/fizzbuzz 18` 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 FizzBuzz!!! 16 17 fizz
いい感じ。成果物です。
コミットの細かさには定評がある僕です。
参考
- Getting Started
- Rust の非公式な対話型シェル「rusti」の紹介 - Qiita
- Cargo Guide
- Arrays and Slices | Rust by Example
- std::env::Args - Rust
- rust - How to access command line parameters? - Stack Overflow
- Guards | Rust by Example
- Primitive Types
- Convert a String to int in Rust? - Stack Overflow
- std::option::Option - Rust
- Argument parsing | Rust by Example
- Patterns
- Functions
- Match
- Rust: Pattern Matching and the Option Type - Nick Desaulniers
-
Option
| Rust by Example - Open Type Switch in Rust — is it possible? : rust
- Simplest way to write "FizzBuzz" in Rust - Code Review Stack Exchange
- What happened to inclusive Ranges? : rust
雑感
- とりあえず書き始めたけど、思ったより難しくて、ちゃんとチュートリアル読まなあかんな、と思った
- わりと楽しく書けそう
Programming Rust: Fast, Safe Systems Development
- 作者: Jim Blandy,Jason Orendorff
- 出版社/メーカー: Oreilly & Associates Inc
- 発売日: 2017/12/21
- メディア: ペーパーバック
- この商品を含むブログを見る