Last active
December 2, 2018 02:02
-
-
Save toshimasa-nanaki/9894822e6cfc581f986247c94383b1df to your computer and use it in GitHub Desktop.
Rust 変数束縛
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//注意!! 勉強メモ用にmainを並べているだけ。 | |
//実際に動かす場合はこの中から一つだけmainを選択すること。 | |
//(1)型推論を利用した宣言 | |
fn main() { | |
let x = 7; | |
println!("x is {}.", x); // x is 7. | |
} | |
//(2)型を定義 | |
fn main() { | |
let x: i32 = 7; //32bit符合付き整数 | |
println!("x is {}.", x); // x is 7. | |
} | |
//(3)デフォルトはイミュータブル(コンパイルエラー) | |
fn main() { | |
let x = 7; | |
x = 8; //こんなことはできない。(デフォルトはイミュータブル(変更不可)だから) | |
println!("x is {}.", x); | |
} | |
//(4)ミュータブルにする | |
fn main() { | |
let mut x = 7; //mutとつければ、ミュータブル(変更可能)と判断される。 | |
x = 8; | |
println!("x is {}.", x); // x is 8. | |
} | |
//(5)初期化していない変数は使えない(コンパイルエラー) | |
fn main() { | |
let x : i32; | |
println!("x is {}.", x); //初期化していないためコンパイル失敗 | |
} | |
//(6)変数のスコープはブロック内で有効(コンパイルエラー) | |
fn main() { | |
let x : i32 = 7; | |
{ | |
let y : i32 = 8; | |
println!("x is {}, y is {}.", x, y); | |
} | |
println!("x is {}, y is {}.", x, y); //ブロック内で宣言されたyは見えないのでコンパイル失敗 | |
} | |
//(7)変数の上書き(シャドーイング) | |
fn main() { | |
let x : i32 = 7; | |
{ | |
println!("x is {}.", x); // x is 7. | |
let x : i32 = 8; | |
println!("x is {}.", x); // x is 8. | |
} | |
println!("x is {}.", x); //x is 7. | |
let x = "test"; | |
println!("x is {}.", x); // x is test. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment