
新聞
透過 OpenCollective 以 3 個簡單步驟成為 Crystal 贊助者
貢獻# A very basic HTTP server
require "http/server"
server = HTTP::Server.new do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world, got #{context.request.path}!"
end
address = server.bind_tcp(8080)
puts "Listening on http://#{address}"
# This call blocks until the process is terminated
server.listen
Crystal 是靜態型別語言,型別錯誤會在編譯器早期被捕獲,從而消除執行時一系列與型別相關的錯誤。
不過,由於強大的型別推斷,很少需要型別註釋。這保持了程式碼的簡潔性,感覺就像動態語言。
def shout(x)
# Notice that both Int32 and String respond_to `to_s`
x.to_s.upcase
end
# If `ENV["FOO"]` is defined, use that, else `10`
foo = ENV["FOO"]? || 10
puts typeof(foo) # => (Int32 | String)
puts typeof(shout(foo)) # => String
nil
值由一個特殊的型別 Nil
表示,任何可以為 nil
的值都具有包含 Nil
的聯合型別。
因此,編譯器可以在編譯時判斷值是否可為空。它會強制明確處理 nil
值,有助於防止可怕的十億美元錯誤。
foo = [nil, "hello world"].sample
# The type of `foo` is a union of `String` and `Nil``
puts typeof(foo) # => String | Nil
# This would be a type error:
# puts foo.upcase # Error: undefined method 'upcase' for Nil
# The condition excludes `Nil` and inside the branch `foo`'s type is `String`.
if foo
puts typeof(foo) # => String
puts foo.upcase
end
class String
def longest_repetition?
max = chars
.chunk(&.itself)
.map(&.last)
.max_by?(&.size)
{max[0], max.size} if max
end
end
puts "aaabb".longest_repetition? # => {'a', 3}
channel = Channel(Int32).new
3.times do |i|
spawn do
3.times do |j|
sleep rand(100).milliseconds # add non-determinism for fun
channel.send 10 * (i + 1) + j
end
end
end
9.times do
puts channel.receive
end
Crystal 允許定義 C 程式庫的綁定並呼叫它們。您可以輕鬆使用現有的豐富程式庫生態系統。
當某些工作已經有好的程式庫時,無需在 Crystal 中實現整個程式。
# Define the lib bindings and link info:
@[Link("m")]
lib LibM
fun pow(x : LibC::Double, y : LibC::Double) : LibC::Double
end
# Call a C function like a Crystal method:
puts LibM.pow(2.0, 4.0) # => 16.0
# This example intentionally uses a simple standard C function to be succinct.
# Of course you could do *this specific* calculation in native Crystal as well:
# 2.0 ** 4.0 # => 16.0
class Object
def has_instance_var?(name) : Bool
{{ @type.instance_vars.map &.name.stringify }}.includes? name
end
end
class Person
property name : String
def initialize(@name)
end
end
person = Person.new "John"
p! person.has_instance_var?("name") # => true
p! person.has_instance_var?("birthday") # => false
Crystal 程式庫透過 Shards 打包,這是一種分散式相依性管理工具,沒有中央儲存庫。
它會讀取在 shard.yml
中定義的相依性,並從其儲存庫中提取原始程式碼。
name: my-first-crystal-app
version: 1.0.0
license: Apache-2.0
authors:
- Crys <crystal@manas.tech>
dependencies:
mysql:
github: crystal-lang/crystal-mysql
version: ~>0.16.0
development_dependencies:
ameba:
github: crystal-ameba/ameba
透過 OpenCollective 以 3 個簡單步驟成為 Crystal 贊助者
貢獻