01
快速上手
Hello World
Crystal 的语法与 Ruby 非常相似。
crystal
puts "Hello, World!"变量
Crystal 中变量默认不可变。
crystal
x = 10 # immutable
y = 20
puts x + y函数
无需显式 return;最后一个表达式就是返回值。
crystal
def add(a, b)
a + b
end
puts add(3, 4)运行与构建
crystal build 生成原生二进制文件。
crystal
# crystal run main.cr
# crystal build main.cr --release02
类型与数据结构
基本类型
Crystal 在编译期自动推断类型。
crystal
i = 1 # Int32
f = 3.14 # Float64
s = "hello" # String
b = true # Bool
a = [1, 2, 3] # Array(Int32)Hash
Hash 等价于 Ruby 的 Hash。
crystal
h = {"a" => 1, "b" => 2}
puts h["a"]
h["c"] = 3元组
元组是固定长度、可含不同类型的数组。
crystal
t = {1, "hello", true}
puts t[0]
puts t[1]命名元组
命名元组以符号(symbol)作为键。
crystal
nt = {x: 1, y: 2}
puts nt[:x]
puts nt[:y]03