04-变量

Wan Yutong Lv2

变量是一个语言中重要的部分,大多数Toy Language都会选择在实现四则计算后,实现变量的存储,Alum也不例外,在Alum中,变量的声明与初始化方式如下:

1
let var: T = value

例如,声明一个变量i,其类型为int,值为1,代码如下:

1
let i: int = 1

需要注意的是,Alum的变量必须在声明的同时初始化,这意味着,即使暂时没有用到它,你也要给他一个值,哪怕是0, 0.0, ''(空字符串),falsenil,并且Alum中并没有变量与常量的区分,默认也没有不可变性,这让语法以及后端实现更简单,但也需要开发者自己保证一个标识符是变量还是常量。另外,Alum也不支持通过extern关键字引入全局变量。
下面给出一个关于变量的例子,出自Alum/examples/02_variables.al

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
$import "io.al"
$import "convert.al"

// Variables Example
// Demonstrates variable declarations with different types

fun main(): int {
// Integer variable
let age: int = 25

// Float variable
let pi: float = 3.14159

// Boolean variable
let is_student: bool = true

// String variable
let name: string = "Alum"

// Nil value for integer
let empty: int = nil

// Print values
println("Name: ")
println(name)
println("Age: ")
println(itoa(age))
println("Pi: ")
println(ftoa(pi))
println("Is Student: ")
if is_student {
println("true")
} else {
println("false")
}

return 0
}

这里可以看到,每次声明并初始化一个变量时,都要显式的标出类型,这虽然清晰,但有时也令代码变得冗长且不必要,比如上面的定义i的值为1,这里很明显i的类型为int,于是我们便可以省略类型,使用Alum自动推导的特性,直接写为:

1
let i = 1

这样在保证代码清晰的同时,也提升了简洁性。

  • Title: 04-变量
  • Author: Wan Yutong
  • Created at : 2026-02-27 14:22:21
  • Updated at : 2026-03-03 11:38:47
  • Link: https://cr0.dpdns.org/2026/02/27/04-Variable/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
04-变量