GitHub 儲存庫 論壇 RSS 新聞 Feed

Crystal

為人類和電腦打造的語言

範例

功能齊全

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

語法

Crystal 的語法很大程度上受到 Ruby 的啟發,因此讀起來很自然,寫起來也很容易,並且對於經驗豐富的 Ruby 開發人員來說,學習曲線較低。

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}

並行模型

Crystal 使用稱為纖程的綠色執行緒來實現並行。纖程透過通道相互通訊,而無需轉向共享記憶體或鎖定 (CSP)。

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

C 綁定

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

巨集

Crystal 對於元程式設計的回應是強大的巨集系統,其範圍從基本範本和 AST 檢視到型別檢視和執行任意外部程式。

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 贊助者

貢獻
企業支援

贊助 Crystal 為您的品牌創造了絕佳的跳板

取得支援
聘請我們來處理您的專案

您可以利用該語言的創造者的專業知識來指導您實作。

聘請我們

頂級贊助者

成功案例