编译
编译运行:
nim c -r greetings.nim
编译正式版:
nim c -d:release greetings.nim
默认编译器会输出运行时的检查,通过 -d:release关掉这些输出
基本
- String : 用
" "
- Char : 用
' '
- 注释 : 单行用
#
,多行用#[]#
也可以用discard
创造块评论:
discard """ You can have any Nim code text commented
out inside this with no indentation restrictions.
yes("May I ask a pointless question?") """
- Number : 可以用下划线:
1_000_000
,包含.
或'e' or 'E'
是浮点数,0x
是16进制,ob
是二进制,0o
是八进制 - var : 声明变量
var x, y: int
var
x, y: int
# a comment can occur here too
a, b, c: string
- const : 常量,表达式必须在编译时可计算
- let :和var类似,但let赋值之后不能变,let和const的区别是let强调不能被二次赋值,const强调在编译时计算值并放到数据部分
const input = readLine(stdin) # Error: constant expression expectedlet
let input = readLine(stdin) # works
流控语句
if语句
let name = readLine(stdin)
if name == "":
echo "Poor soul, you lost your name?"
elif name == "name":
echo "Very funny, your name is name."
else:
echo "Hi, ", name, "!"
Case 语句
let name = readLine(stdin)
case name
of "":
echo "Poor soul, you lost your name?"
of "name":
echo "Very funny, your name is name."
of "Dave", "Frank":
echo "Cool name!"
else:
echo "Hi, ", name, "!"
可以看出,对于分支,也允许使用逗号分隔的值列表。
case语句可以处理整数,其他序数类型和字符串。(将很快解释什么是序数类型。)对于整数或其他序数类型,一个范围的值也是可能的:
from strutils import parseInt
echo "A number please: "
let n = parseInt(readLine(stdin))
case n
of 0..2, 4..7: echo "The number is in the set: {0, 1, 2, 4, 5, 6, 7}"
of 3, 8: echo "The number is 3 or 8"
else: discard