0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustの特徴的なところ(構文編)

Last updated at Posted at 2020-04-03

Rustを勉強中ですが、押さえておいた方が良いなという構文をまとめました。
Ownershipは別立てでまとめようと思ってます。

変数のmutable/immutable

並行プログラミングを安全・簡単に記述するための"nudge"の1つ
筆者私見: ある処理ブロックの中で変数が変わらないことを保証する役目

let x = 5;
x = 6; // できない!!
let mut x = 5;
x = 6; // できる!!

ただしimmutableでも下記のようなreassignはできる

let x = 5;
let x = 6; // できる!!

またimmutableでも型が違う値は代入できない

let mut x = 5;
x = "5"; // できない!!

しかし、reassignでは違う型を代入できる(新しい宣言なので当たり前か)

let x = 5;
let x = "6"; // できる!!

データ型

Rustは静的型付け言語
そのためコンパイラに教えるためのtype annotationが必要

let guess: u32 = "42".parse().expect("Not a number!"); // 非負整数であることをannotationする必要がある

これはResult型でも一緒

let res: Result<u32, ParseIntError> = "-42".parse();    
match res {
    Ok(n) => println!("{}", n),
    Err(err) => println!("Error: {:?}", err),
}

データ型は以下の二種類に分かれる

  • Scalar
  • Compound

Scalarは整数型などの、単一値で
Compoundはtuple, arrayの複数値をもつ型

Function

基本的に他の言語とほとんど同じ
ただし返り値にreturnがいらない。(あっても良い)

fn ret_test() -> i32 {
    let x = 5;
    x
}

また、Statementには返り値の概念はないが、Expressionには返り値の概念がある。
下記もExpressionの1つ

let y = {
    let x = 5;
    x
};
// y => 5

関連して、ifもExpressionなので以下のような書き方ができる

let number = if condition {
    5
} else {
    6
};
// condition = true なら number => 5

Control flow

loop構文がある。
breakした値を返り値とできる。

let mut index = 0;
let result = loop {
    println!("loop!");
    index += 1;
    if index == 5 {
        break index;
    }
};

ちなみにwhileやforでは常に空のtupleが返却される。

let result2 = while index < 10 {
     println!("the value is: {}", index);
     index += 1;
};
println!("result2 {:?}", result2); // => result2 ()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?