常值 Literals
Crystal 中有許多可以用來表達基本型別常值的寫法。
我們會在接下來的子章節裡一一介紹。
| 常值 | 舉例 |
|---|---|
| 空值 (Nil) | nil |
| 布林值 (Bool) | true, false |
| 整數 (Integers) | 18, -12, 19_i64, 14_u32,64_u8 |
| 浮點數 (Floats) | 1.0, 1.0_f32, 1e10, -0.5 |
| 字元 (Char) | 'a', '\n', 'あ' |
| 字串 (String) | "foo\tbar", %("あ"), %q(foo #{foo}) |
| 符號 (Symbol) | :symbol, :"foo bar" |
| 陣列 (Array) | [1, 2, 3], [1, 2, 3] of Int32, %w(one two three) |
| 類・陣列 (Array-like) | Set{1, 2, 3} |
| 雜湊 (Hash) | {"foo" => 2}, {} of String => Int32 |
| 類・雜湊 (Hash-like) | MyType{"foo" => "bar"} |
| 範圍 (Range) | 1..9, 1...10, 0..var |
| 正規表達式 (Regex) | /(foo)?bar/, /foo #{foo}/imx, %r(foo/) |
| 序組 (Tuple) | {1, "hello", 'x'} |
| 命名序組 (NamedTuple) | {name: "Crystal", year: 2011}, {"this is a key": 1} |
| 程序 (Proc) | ->(x : Int32, y : Int32) { x + y } |
| Command | `echo foo` , %x(echo foo) |
譯註
常值(Literal),相對於常數(Constant),僅描述了所代表的值(Value),有時也會稱為字面常值(Literal constant)。