100天学习mojo-day2语言元素

277 阅读2分钟

欢迎关注github项目,100天Mojo从新手到大师

github.com/wusiyaodiud…

语言元素

变量和类型

变量的命名

可以使用 var 声明一个可变变量,或使用 let 创建不可变值。 在变量名后使用 : 声明变量类型,例如:

var x: Int = 1
let y: Int = 2

同样兼容Python的不声明变量可不可变以及变量类型的写法,例如:a = 1

变量的使用

下面通过几个例子来说明变量的类型和变量使用。

使用变量保存数据并进行加减乘除运算
let a: Int = 321
let b: Int = 12
print(a + b)    # 333
print(a - b)    # 309
print(a * b)    # 3852
print(a / b)    # 26.75

检查变量类型

根据issue中所述,Mojo 目前没有 type() 方法,是因为还没有一个运行时类型表示。例如,在 Python 中,type() 方法返回一个可以像类一样使用的类型实例。可以通过调用 Python 的 type() 方法来查看变量类型。

from python import Python
let py = Python.import_module("builtins")
let a: Int = 100
let b: FloatLiteral = 12.345
let c: String = 'hello, world'
let d: Bool = True
py.print(py.type(a))  # <class 'int'>
py.print(py.type(b))  # <class 'float'>
py.print(py.type(c))  # <class 'str'>
py.print(py.type(d))  # <class 'bool'>

类型转换

Mojo 中进行类型转换需要使用内置的 rebind 方法,类似于 C++ 中 reinterpret_cast的概念。

使用方法为:

rebind[dest_type: AnyType, src_type: AnyType](val: src_type) -> dest_type`
# 参数:
# dest_type(AnyType):要重新绑定到的类型。
# src_type(AnyType):原始类型。
# val(src_type):要重新绑定的值。
# 返回类型:
# dest_type

数字和字符串

整数

使用 Int 类型声明的变量。

浮点数

使用 FloatLiteral 类型声明的变量。

字符串

使用 String 类型声明的变量。

使用 StringLiteral 类型声明的变量。

使用 StringRef 类型声明的变量。

TODO:三种字符串类型的区别