From dd48cb9644eba3a54d959ef0fc6516de3ba5d00f Mon Sep 17 00:00:00 2001 From: Eiji Tanaka Date: Wed, 6 Oct 2021 14:26:02 +0900 Subject: [PATCH] 20211006 static and const --- 3/3-3_static-const | 32 ++++++++++++++++++++++++++++++++ 4/4_variable_binding | 26 ++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 3/3-3_static-const create mode 100644 4/4_variable_binding diff --git a/3/3-3_static-const b/3/3-3_static-const new file mode 100644 index 0000000..b0e7358 --- /dev/null +++ b/3/3-3_static-const @@ -0,0 +1,32 @@ +// Globals are declared outside all other scopes. +// グローバル変数はあらゆるスコープの外で宣言します +static LANGUAGE: &str = "Rust"; +const THRESHOLD: i32 = 10; + +fn is_big(n: i32) -> bool { + // Access constant in some function + // 関数内から定数を参照 + n > THRESHOLD +} + +fn main() { + let n = 16; + + // 基本的にstatic変数は変えちゃ駄目。変えられる方法もあるが面倒。単純に以下の様に代入するとエラー + // なので基本的にはconstを使う。static使うのはほぼ無い。 + // lazy_staticとかonce_cellとか。上級者向け。 + // 参考:https://zenn.dev/frozenlib/articles/lazy_static_to_once_cell + // LANGUAGE = "it's rust."; + + // Access constant in the main thread + // main 関数の中から定数を参照 + println!("This is {}", LANGUAGE); + println!("The threshold is {}", THRESHOLD); + println!("{} is {}", n, if is_big(n) { "big" } else { "small" }); + + // Error! Cannot modify a `const`. + // エラー!`const`は変更できません。 + // THRESHOLD = 5; + // FIXME ^ Comment out this line + // FIXME ^ この行をコメントアウトしましょう +} \ No newline at end of file diff --git a/4/4_variable_binding b/4/4_variable_binding new file mode 100644 index 0000000..ae3c63b --- /dev/null +++ b/4/4_variable_binding @@ -0,0 +1,26 @@ +fn main() { + let an_integer = 1u32; + let a_boolean = true; + let unit = (); + + // copy `an_integer` into `copied_integer` + // `an_integer`を`copied_integer`へとコピー + let copied_integer = an_integer; + + println!("An integer: {:?}", copied_integer); + println!("A boolean: {:?}", a_boolean); + println!("Meet the unit value: {:?}", unit); + + // The compiler warns about unused variable bindings; these warnings can + // be silenced by prefixing the variable name with an underscore + // 使用されていない変数があると、コンパイラは警告を出します。 + // 変数名の頭に`_`(アンダーバー)を付けると警告を消すことができます。 + let _unused_variable = 3u32; + + let _noisy_unused_variable = 2u32; + // FIXME ^ Prefix with an underscore to suppress the warning + // FIXME ^ 頭にアンダーバーを付けて、警告を抑えましょう。 + + // https://doc.rust-jp.rs/rust-by-example-ja/variable_bindings.html の実行では警告が出ない。 + // https://play.rust-lang.org/ で実行するとちゃんと警告が出る。 +} \ No newline at end of file