ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【Rust】入門してみました①

Rust の勉強をしてみたのでここにメモを残します。

sample 01

コード

fn main() {
    let a = "sample 01"; // immutable object
    let b = a;           // copy
    print!("{} {}\n", a, b);
}

ビルド

$ rustc sample_01.rs -o sample_01

実行

$ ./sample_01 
sample 01 sample 01

sample 02

コード

fn main() {
  println!("Hello world!");
  println!("Hello {}!", "world");
  
  let s = format!("Hello {}", "world");
  println!("{}!", s)
}

ビルド

$ rustc sample_02.rs -o sample_02

実行

$ ./sample_02
Hello world!
Hello world!
Hello world!

sample 03

コード

: 条件指定
<n n桁で左寄せ
>n n桁で右寄せ
^n n桁で中央寄せ
>0n 0埋め
fn main() {
  println!("{0: <8} | {1: >8} | {2: ^8} | {3: <08} | {4: >08} | {hundred: >08}",
           "Left",
           "Right",
           "Center",
           1234,
           999,
           hundred=100);
}

ビルド

$ rustc sample_03.rs -o sample_03

実行

$ ./sample_03    
Left     |    Right |  Center  | 00001234 | 00000999 | 00000100

sample 04

コード

b バイナリ
o 8進数
x 16進数
e 指数
fn main() {
  println!("{:b}", 123456789);
  println!("{:o}", 123456789);
  println!("{:x}", 123456789);
  println!("{:X}", 123456789);
  println!("{:e}", 12.3456789);
  println!("{:E}", 12.3456789);
}

ビルド

$ rustc sample_04.rs -o sample_04

実行

$ ./sample_04
111010110111100110100010101
726746425
75bcd15
75BCD15
1.23456789e1
1.23456789E1