Skip to content

Commit 7525573

Browse files
authored
Merge pull request #16 from silverbox/20211006-conststatic
20211006 static and const
2 parents a83617c + dd48cb9 commit 7525573

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

3/3-3_static-const

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Globals are declared outside all other scopes.
2+
// グローバル変数はあらゆるスコープの外で宣言します
3+
static LANGUAGE: &str = "Rust";
4+
const THRESHOLD: i32 = 10;
5+
6+
fn is_big(n: i32) -> bool {
7+
// Access constant in some function
8+
// 関数内から定数を参照
9+
n > THRESHOLD
10+
}
11+
12+
fn main() {
13+
let n = 16;
14+
15+
// 基本的にstatic変数は変えちゃ駄目。変えられる方法もあるが面倒。単純に以下の様に代入するとエラー
16+
// なので基本的にはconstを使う。static使うのはほぼ無い。
17+
// lazy_staticとかonce_cellとか。上級者向け。
18+
// 参考:https://zenn.dev/frozenlib/articles/lazy_static_to_once_cell
19+
// LANGUAGE = "it's rust.";
20+
21+
// Access constant in the main thread
22+
// main 関数の中から定数を参照
23+
println!("This is {}", LANGUAGE);
24+
println!("The threshold is {}", THRESHOLD);
25+
println!("{} is {}", n, if is_big(n) { "big" } else { "small" });
26+
27+
// Error! Cannot modify a `const`.
28+
// エラー!`const`は変更できません。
29+
// THRESHOLD = 5;
30+
// FIXME ^ Comment out this line
31+
// FIXME ^ この行をコメントアウトしましょう
32+
}

4/4_variable_binding

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
fn main() {
2+
let an_integer = 1u32;
3+
let a_boolean = true;
4+
let unit = ();
5+
6+
// copy `an_integer` into `copied_integer`
7+
// `an_integer`を`copied_integer`へとコピー
8+
let copied_integer = an_integer;
9+
10+
println!("An integer: {:?}", copied_integer);
11+
println!("A boolean: {:?}", a_boolean);
12+
println!("Meet the unit value: {:?}", unit);
13+
14+
// The compiler warns about unused variable bindings; these warnings can
15+
// be silenced by prefixing the variable name with an underscore
16+
// 使用されていない変数があると、コンパイラは警告を出します。
17+
// 変数名の頭に`_`(アンダーバー)を付けると警告を消すことができます。
18+
let _unused_variable = 3u32;
19+
20+
let _noisy_unused_variable = 2u32;
21+
// FIXME ^ Prefix with an underscore to suppress the warning
22+
// FIXME ^ 頭にアンダーバーを付けて、警告を抑えましょう。
23+
24+
// https://doc.rust-jp.rs/rust-by-example-ja/variable_bindings.html の実行では警告が出ない。
25+
// https://play.rust-lang.org/ で実行するとちゃんと警告が出る。
26+
}

0 commit comments

Comments
 (0)