跳至內容

開始使用

您好,歡迎來到 Crystal 的參考書!

首先,請務必安裝編譯器,以便我們可以嘗試本書中列出的所有範例。

安裝完成後,Crystal 編譯器應該可以透過 crystal 命令使用。

讓我們試試看!

Crystal 版本

我們可以檢查 Crystal 編譯器的版本。如果 Crystal 安裝正確,我們應該會看到類似這樣的資訊

$ crystal --version
Crystal 1.14.0 [dacd97bcc] (2024-10-09)

LLVM: 18.1.6
Default target: x86_64-unknown-linux-gnu

太棒了!

Crystal 說明

現在,如果我們要列出編譯器提供的所有選項,我們可以執行不帶任何引數的 crystal 程式

$ crystal
Usage: crystal [command] [switches] [program file] [--] [arguments]

Command:
    init                     generate a new project
    build                    build an executable
    docs                     generate documentation
    env                      print Crystal environment information
    eval                     eval code from args or standard input
    play                     starts Crystal playground server
    run (default)            build and run program
    spec                     build and run specs (in spec directory)
    tool                     run a tool
    help, --help, -h         show this help
    version, --version, -v   show version

Run a command followed by --help to see command-specific information, ex:
    crystal <command> --help

關於使用編譯器的更多詳細資訊,可以在 manpage man crystal 或我們的編譯器手冊中找到。

Hello Crystal

以下範例是經典的 Hello World。在 Crystal 中,它看起來像這樣

hello_world.cr
puts "Hello World!"

我們可以這樣執行我們的範例

$ crystal hello_world.cr
Hello World!

注意

主常式就是程式本身。無需定義「main」函式或類似的東西。

接下來,您可能想要從導覽簡介開始,以熟悉這門語言。

這裡我們還有兩個範例,可以繼續我們在 Crystal 中的第一步