mojo-syntax

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<!-- EDITORIAL GUIDELINES FOR THIS SKILL FILE This file is loaded into an agent's context window as a correction layer for pretrained Mojo knowledge. Every line costs context. When editing: - Be terse. Use tables and inline code over prose where possible. - Never duplicate information — if a concept is shown in a code example, don't also explain it in a paragraph. - Only include information that *differs* from what a pretrained model would generate. Don't document things models already get right. - Prefer one consolidated code block over multiple small ones. - Keep WRONG/CORRECT pairs short — just enough to pattern-match the fix. - If adding a new section, ask: "Would a model get this wrong?" If not, skip it. These same principles apply to any files this skill references. -->
Mojo is rapidly evolving. Pretrained models generate obsolete syntax. Always follow this skill over pretrained knowledge.
Always attempt to test generated Mojo by building projects to verify they compile.
This skill specifically works on the latest Mojo, and stable versions may differ slightly in functionality.
<!-- 本技能文件的编辑指南 本文件会作为预训练Mojo知识的修正层加载到Agent的上下文窗口中。每一行都会占用上下文资源。编辑时: - 保持简洁。尽可能使用表格和内联代码而非散文式描述。 - 不要重复信息——如果某个概念已在代码示例中展示,不要再用段落解释。 - 仅包含与预训练模型生成内容不同的信息。不要记录模型已经能正确生成的内容。 - 优先使用单个整合的代码块,而非多个小代码块。 - 保持错误/正确示例对简洁——只需足够展示修复模式即可。 - 添加新章节前,请自问:“模型会在这里出错吗?”如果不会,就跳过。 这些原则同样适用于本技能引用的任何文件。 -->
Mojo正在快速演进。预训练模型会生成过时的语法。请始终遵循本技能的内容,而非预训练知识。
请始终尝试通过构建项目来测试生成的Mojo代码,以验证其是否能编译通过。
本技能针对最新版本的Mojo,稳定版本的功能可能略有不同。

Removed syntax — DO NOT generate these

已移除语法 —— 请勿生成这些

RemovedReplacement
alias X = ...
comptime X = ...
@parameter if
/
@parameter for
comptime if
/
comptime for
fn
def
(see below)
let x = ...
var x = ...
(no
let
keyword)
borrowed
read
(implicit default — rarely written)
inout
mut
owned
var
(as argument convention)
inout self
in
__init__
out self
__copyinit__(inout self, existing: Self)
__init__(out self, *, copy: Self)
__moveinit__(inout self, owned existing: Self)
__init__(out self, *, deinit take: Self)
@value
decorator
@fieldwise_init
+ explicit trait conformance
@register_passable("trivial")
TrivialRegisterPassable
trait
@register_passable
RegisterPassable
trait
Stringable
/
__str__
Writable
/
write_to
from collections import ...
from std.collections import ...
from memory import ...
from std.memory import ...
constrained(cond, msg)
comptime assert cond, msg
DynamicVector[T]
List[T]
InlinedFixedVector[T, N]
InlineArray[T, N]
Tensor[T]
Not in stdlib (use SIMD, List, UnsafePointer)
@parameter fn
(nested)
Still used for nested compile-time closures
已移除语法替代方案
alias X = ...
comptime X = ...
@parameter if
/
@parameter for
comptime if
/
comptime for
fn
def
(见下文)
let x = ...
var x = ...
(无
let
关键字)
borrowed
read
(隐式默认——很少需要显式编写)
inout
mut
owned
var
(作为参数约定)
__init__
中的
inout self
out self
__copyinit__(inout self, existing: Self)
__init__(out self, *, copy: Self)
__moveinit__(inout self, owned existing: Self)
__init__(out self, *, deinit take: Self)
@value
装饰器
@fieldwise_init
+ 显式trait实现
@register_passable("trivial")
TrivialRegisterPassable
trait
@register_passable
RegisterPassable
trait
Stringable
/
__str__
Writable
/
write_to
from collections import ...
from std.collections import ...
from memory import ...
from std.memory import ...
constrained(cond, msg)
comptime assert cond, msg
DynamicVector[T]
List[T]
InlinedFixedVector[T, N]
InlineArray[T, N]
Tensor[T]
不在标准库中(使用SIMD、List、UnsafePointer)
嵌套的
@parameter fn
仍用于嵌套编译时闭包

def
is the only function keyword

def
是唯一的函数关键字

fn
is deprecated and being removed.
def
does not imply
raises
. Always add
raises
explicitly when needed — omitting it is a warning today, error soon:
mojo
def compute(x: Int) -> Int:              # non-raising (compiler enforced)
    return x * 2

def load(path: String) raises -> String: # explicitly raising
    return open(path).read()

def main() raises:                       # main usually raises → def raises
    ...
Note: existing stdlib code still uses
fn
during migration. New code should always use
def
.
fn
已被废弃并将被移除。
def
并不意味着
raises
当需要时请始终显式添加
raises
——目前省略它只会发出警告,但很快会变成错误:
mojo
def compute(x: Int) -> Int:              # 不抛出异常(编译器强制检查)
    return x * 2

def load(path: String) raises -> String: # 显式声明抛出异常
    return open(path).read()

def main() raises:                       # main通常会抛出异常 → 使用def raises
    ...
注意:现有标准库代码在迁移期间仍会使用
fn
。新代码应始终使用
def

comptime
replaces
alias
and
@parameter

comptime
替代
alias
@parameter

mojo
comptime N = 1024                            # compile-time constant
comptime MyType = Int                        # type alias
comptime if condition:                       # compile-time branch
    ...
comptime for i in range(10):                 # compile-time loop
    ...
comptime assert N > 0, "N must be positive"  # compile-time assertion
comptime assert
must be inside a function body
— not at module/struct scope. Place them in
main()
,
__init__
, or the function that depends on the invariant.
Inside structs,
comptime
defines associated constants and type aliases:
mojo
struct MyStruct:
    comptime DefaultSize = 64
    comptime ElementType = Float32
mojo
comptime N = 1024                            # 编译时常量
comptime MyType = Int                        # 类型别名
comptime if condition:                       # 编译时分支
    ...
comptime for i in range(10):                 # 编译时循环
    ...
comptime assert N > 0, "N must be positive"  # 编译时断言
comptime assert
必须放在函数体内
——不能在模块/结构体作用域中。请将它们放在
main()
__init__
或依赖该不变量的函数中。
在结构体内部,
comptime
用于定义关联常量和类型别名:
mojo
struct MyStruct:
    comptime DefaultSize = 64
    comptime ElementType = Float32

Argument conventions

参数约定

Default is
read
(immutable borrow, never written explicitly). The others:
mojo
def __init__(out self, var value: String):   # out = uninitialized output; var = owned
def modify(mut self):                         # mut = mutable reference
def consume(deinit self):                     # deinit = consuming/destroying
def view(ref self) -> ref[self] Self.T:       # ref = reference with origin
def view2[origin: Origin, //](ref[origin] self) -> ...:           # ref[origin] = explicit origin
默认是
read
(不可变借用,无需显式编写)。其他类型如下:
mojo
def __init__(out self, var value: String):   # out = 未初始化的输出参数;var = 拥有所有权
    def modify(mut self):                         # mut = 可变引用
        def consume(deinit self):                     # deinit = 消耗/销毁
            def view(ref self) -> ref[self] Self.T:       # ref = 带来源的引用
                def view2[origin: Origin, //](ref[origin] self) -> ...:           # ref[origin] = 显式指定来源
                    ...

Lifecycle methods

生命周期方法

mojo
undefined
mojo
undefined

Constructor

构造函数

def init(out self, x: Int): self.x = x
def init(out self, x: Int): self.x = x

Copy constructor (keyword-only
copy
arg)

复制构造函数(仅关键字参数
copy

def init(out self, *, copy: Self): self.data = copy.data
def init(out self, *, copy: Self): self.data = copy.data

Move constructor (keyword-only
deinit take
arg)

移动构造函数(仅关键字参数
deinit take

def init(out self, *, deinit take: Self): self.data = take.data^
def init(out self, *, deinit take: Self): self.data = take.data^

Destructor

析构函数

def del(deinit self): self.ptr.free()

To copy: `var b = a.copy()` (provided by `Copyable` trait).
def del(deinit self): self.ptr.free()

复制对象:`var b = a.copy()`(由`Copyable` trait提供)。

Struct patterns

结构体模式

mojo
undefined
mojo
undefined

@fieldwise_init generates init from fields; traits in parentheses

@fieldwise_init 会根据字段生成__init__;括号中是实现的trait

@fieldwise_init struct Point(Copyable, Movable, Writable): var x: Float64 var y: Float64
@fieldwise_init struct Point(Copyable, Movable, Writable): var x: Float64 var y: Float64

Trait composition with &

使用&组合trait

comptime KeyElement = Copyable & Hashable & Equatable struct Node[T: Copyable & Writable]: var value: Self.T # Self-qualify struct parameters
comptime KeyElement = Copyable & Hashable & Equatable struct Node[T: Copyable & Writable]: var value: Self.T # 使用Self限定结构体参数

Parametric struct — // separates inferred from explicit params

参数化结构体 —— // 分隔推断参数和显式参数

struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]( ImplicitlyCopyable, Sized, ): ...
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]( ImplicitlyCopyable, Sized, ): ...

@implicit on constructors allows implicit conversion

构造函数上的@implicit允许隐式转换

@implicit def init(out self, value: Int): self.data = value

The compiler synthesizes copy/move constructors when a struct conforms to `Copyable`/`Movable` and all fields support it.
@implicit def init(out self, value: Int): self.data = value

当结构体实现`Copyable`/`Movable`且所有字段都支持时,编译器会自动生成复制/移动构造函数。

Self-qualify struct parameters

使用Self限定结构体参数

Inside a struct body, always use
Self.ParamName
— bare parameter names are errors:
mojo
undefined
在结构体内部,必须使用
Self.ParamName
——直接使用参数名称会报错:
mojo
undefined

WRONG — bare parameter access

错误示例 —— 直接访问参数

struct Container[T: Writable]: var data: T # ERROR: use Self.T def size(self) -> T: # ERROR: use Self.T
struct Container[T: Writable]: var data: T # 错误:应使用Self.T def size(self) -> T: # 错误:应使用Self.T

CORRECT — Self-qualified

正确示例 —— 使用Self限定

struct Container[T: Writable]: var data: Self.T def size(self) -> Self.T: return self.data

This applies to all struct parameters (`T`, `N`, `mut`, `origin`, etc.) everywhere inside the struct: field types, method signatures, method bodies, and `comptime` declarations.
struct Container[T: Writable]: var data: Self.T def size(self) -> Self.T: return self.data

这适用于结构体的所有参数(`T`、`N`、`mut`、`origin`等),包括字段类型、方法签名、方法体和`comptime`声明。

Explicit copy / transfer

显式复制/转移

Types not conforming to
ImplicitlyCopyable
(e.g.,
Dict
,
List
) require explicit
.copy()
or ownership transfer
^
:
mojo
undefined
未实现
ImplicitlyCopyable
的类型(如
Dict
List
)需要显式调用
.copy()
或使用所有权转移操作符
^
mojo
undefined

WRONG — implicit copy of non-ImplicitlyCopyable type

错误示例 —— 隐式复制非ImplicitlyCopyable类型

var d = some_dict var result = MyStruct(headers=d) # ERROR
var d = some_dict var result = MyStruct(headers=d) # 错误

CORRECT — explicit copy or transfer

正确示例 —— 显式复制或转移所有权

var result = MyStruct(headers=d.copy()) # or: headers=d^
undefined
var result = MyStruct(headers=d.copy()) # 或者:headers=d^
undefined

Imports use
std.
prefix

导入需使用
std.
前缀

mojo
from std.testing import assert_equal, TestSuite
from std.algorithm import vectorize
from std.python import PythonObject
import std.random
Prelude auto-imports (no import needed):
Int
,
String
,
Bool
,
List
,
Dict
,
Optional
,
SIMD
,
Float32
,
Float64
,
UInt8
,
Pointer
,
UnsafePointer
,
Span
,
Error
,
DType
,
Writable
,
Writer
,
Copyable
,
Movable
,
Equatable
,
Hashable
,
rebind
,
print
,
range
,
len
, and more.
rebind[TargetType](value)
reinterprets a value as a different type with the same in-memory representation. Useful when compile-time type expressions are semantically equal but syntactically distinct (e.g., LayoutTensor element types — see GPU skill).
mojo
from std.testing import assert_equal, TestSuite
from std.algorithm import vectorize
from std.python import PythonObject
import std.random
预导入的内容(无需手动导入):
Int
String
Bool
List
Dict
Optional
SIMD
Float32
Float64
UInt8
Pointer
UnsafePointer
Span
Error
DType
Writable
Writer
Copyable
Movable
Equatable
Hashable
rebind
print
range
len
等。
rebind[TargetType](value)
用于将值重新解释为内存表示相同的其他类型。当编译时类型表达式语义等价但语法不同时非常有用(例如LayoutTensor元素类型——请参考GPU技能)。

Writable
/
Writer
(replaces
Stringable
)

Writable
/
Writer
(替代
Stringable

mojo
struct MyType(Writable):
    var x: Int

    def write_to(self, mut writer: Some[Writer]):       # for print() / String()
        writer.write("MyType(", self.x, ")")

    def write_repr_to(self, mut writer: Some[Writer]):   # for repr()
        t"MyType(x={self.x})".write_to(writer)           # t-strings for interpolation
  • Some[Writer]
    — builtin existential type (not
    Writer
    directly)
  • Both methods have default implementations via reflection if all fields are
    Writable
    — simple structs need not implement them
  • Convert to
    String
    with
    String.write(value)
    , not
    str(value)
mojo
struct MyType(Writable):
    var x: Int

    def write_to(self, mut writer: Some[Writer]):       # 用于print() / String()
        writer.write("MyType(", self.x, ")")

    def write_repr_to(self, mut writer: Some[Writer]):   # 用于repr()
        t"MyType(x={self.x})".write_to(writer)           # 使用t-string进行插值
  • Some[Writer]
    —— 内置存在类型(不是直接使用
    Writer
  • 如果所有字段都是
    Writable
    ,这两个方法都有默认实现(通过反射)——简单结构体无需手动实现
  • 使用
    String.write(value)
    转换为
    String
    ,而非
    str(value)

Iterator protocol

迭代器协议

Iterators use
raises StopIteration
(not
Optional
):
mojo
struct MyCollection(Iterable):
    comptime IteratorType[
        iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
    ]: Iterator = MyIter[origin=iterable_origin]

    def __iter__(ref self) -> Self.IteratorType[origin_of(self)]: ...
迭代器使用
raises StopIteration
(而非
Optional
):
mojo
struct MyCollection(Iterable):
    comptime IteratorType[
        iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
    ]: Iterator = MyIter[origin=iterable_origin]

    def __iter__(ref self) -> Self.IteratorType[origin_of(self)]: ...

Iterator must define:

迭代器必须定义:

comptime Element: Movable

comptime Element: Movable

def next(mut self) raises StopIteration -> Self.Element

def next(mut self) raises StopIteration -> Self.Element


For-in: `for item in col:` (immutable) / `for ref item in col:` (mutable).

For-in循环:`for item in col:`(不可变)/ `for ref item in col:`(可变)。

Memory and pointer types

内存和指针类型

TypeUse
Pointer[T, mut=M, origin=O]
Safe, non-nullable. Deref with
p[]
.
alloc[T](n)
/
UnsafePointer
Free function
alloc[T](count)
UnsafePointer
.
.free()
required.
Span(list)
Non-owning contiguous view.
OwnedPointer[T]
Unique ownership (like Rust
Box
).
ArcPointer[T]
Reference-counted shared ownership.
UnsafePointer
has an
origin
parameter that must be specified for struct fields. Use
MutExternalOrigin
for owned heap data (this is what stdlib
ArcPointer
uses):
mojo
undefined
类型用途
Pointer[T, mut=M, origin=O]
安全、非空指针。使用
p[]
解引用。
alloc[T](n)
/
UnsafePointer
自由函数
alloc[T](count)
返回
UnsafePointer
。必须调用
.free()
释放。
Span(list)
非所有权的连续内存视图。
OwnedPointer[T]
唯一所有权(类似Rust的
Box
)。
ArcPointer[T]
引用计数的共享所有权。
UnsafePointer
有一个
origin
参数,结构体字段中必须指定该参数。对于自有堆内存,使用
MutExternalOrigin
(标准库中的
ArcPointer
就是用的这个):
mojo
undefined

Struct field — specify origin explicitly

结构体字段 —— 显式指定origin

var _ptr: UnsafePointer[Self.T, MutExternalOrigin]
var _ptr: UnsafePointer[Self.T, MutExternalOrigin]

Allocate with alloc[]

使用alloc[]分配内存

fn init(out self, size: Int): self._ptr = allocSelf.T
undefined
fn init(out self, size: Int): self._ptr = allocSelf.T
undefined

Origin system (not "lifetime")

来源系统(非“生命周期”)

Mojo tracks reference provenance with origins, not "lifetimes":
mojo
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...
Key types:
Origin
,
MutOrigin
,
ImmutOrigin
,
MutAnyOrigin
,
ImmutAnyOrigin
,
MutExternalOrigin
,
ImmutExternalOrigin
,
StaticConstantOrigin
. Use
origin_of(value)
to get a value's origin.
Mojo使用**来源(origin)**而非“生命周期”来跟踪引用的溯源:
mojo
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...
关键类型:
Origin
MutOrigin
ImmutOrigin
MutAnyOrigin
ImmutAnyOrigin
MutExternalOrigin
ImmutExternalOrigin
StaticConstantOrigin
。使用
origin_of(value)
获取值的来源。

Testing

测试

mojo
from std.testing import assert_equal, assert_true, assert_false, assert_raises, TestSuite

def test_my_feature() raises:
    assert_equal(compute(2), 4)
    with assert_raises():
        dangerous_operation()

def main() raises:
    TestSuite.discover_tests[__functions_in_module()]().run()
mojo
from std.testing import assert_equal, assert_true, assert_false, assert_raises, TestSuite

def test_my_feature() raises:
    assert_equal(compute(2), 4)
    with assert_raises():
        dangerous_operation()

def main() raises:
    TestSuite.discover_tests[__functions_in_module()]().run()

Dict iteration

Dict迭代

Dict entries are iterated directly — no
[]
deref:
mojo
for entry in my_dict.items():
    print(entry.key, entry.value)      # direct field access, NOT entry[].key

for key in my_dict:
    print(key, my_dict[key])
直接迭代Dict的条目——无需
[]
解引用:
mojo
for entry in my_dict.items():
    print(entry.key, entry.value)      # 直接访问字段,而非entry[].key

for key in my_dict:
    print(key, my_dict[key])

Collection literals

集合字面量

List
has no variadic positional constructor. Use bracket literal syntax:
mojo
undefined
List
没有可变参数构造函数。请使用方括号字面量语法:
mojo
undefined

WRONG — no List[T](elem1, elem2, ...) constructor

错误示例 —— 没有List[T](elem1, elem2, ...)构造函数

var nums = List[Int](1, 2, 3)
var nums = List[Int](1, 2, 3)

CORRECT — bracket literals

正确示例 —— 方括号字面量

var nums = [1, 2, 3] # List[Int] var nums: List[Float32] = [1.0, 2.0, 3.0] # explicit element type var scores = {"alice": 95, "bob": 87} # Dict[String, Int]
undefined
var nums = [1, 2, 3] # List[Int] var nums: List[Float32] = [1.0, 2.0, 3.0] # 显式指定元素类型 var scores = {"alice": 95, "bob": 87} # Dict[String, Int]
undefined

Common decorators

常用装饰器

DecoratorPurpose
@fieldwise_init
Generate fieldwise constructor
@implicit
Allow implicit conversion
@always_inline
/
@always_inline("nodebug")
Force inline
@no_inline
Prevent inline
@staticmethod
Static method
@deprecated("msg")
Deprecation warning
@doc_private
Hide from docs
@explicit_destroy
Linear type (no implicit destruction)
装饰器用途
@fieldwise_init
生成基于字段的构造函数
@implicit
允许隐式转换
@always_inline
/
@always_inline("nodebug")
强制内联
@no_inline
禁止内联
@staticmethod
静态方法
@deprecated("msg")
发出弃用警告
@doc_private
在文档中隐藏
@explicit_destroy
线性类型(无隐式销毁)

Numeric conversions — must be explicit

数值转换 —— 必须显式进行

No implicit conversions between numeric variables. Use explicit constructors:
mojo
var x = Float32(my_int) * scale    # CORRECT: Int → Float32
var y = Int(my_uint)               # CORRECT: UInt → Int
Literals are polymorphic
FloatLiteral
and
IntLiteral
auto-adapt to context:
mojo
var a: Float32 = 0.5              # literal becomes Float32
var b = Float32(x) * 0.003921    # literal adapts — no wrapping needed
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)  # literals adapt
数值变量之间没有隐式转换。请使用显式构造函数:
mojo
var x = Float32(my_int) * scale    # 正确:Int → Float32
var y = Int(my_uint)               # 正确:UInt → Int
字面量是多态的——
FloatLiteral
IntLiteral
会自动适配上下文:
mojo
var a: Float32 = 0.5              # 字面量会变为Float32类型
var b = Float32(x) * 0.003921    # 字面量自动适配——无需包装
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)  # 字面量自动适配

SIMD operations

SIMD操作

mojo
undefined
mojo
undefined

Construction and lane access

构造和通道访问

var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0) v[0] # read lane → Scalar[DType.float32] v[0] = 5.0 # write lane
var v = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0) v[0] # 读取通道 → Scalar[DType.float32] v[0] = 5.0 # 写入通道

Type cast

类型转换

v.castDType.uint32 # element-wise → SIMD[DType.uint32, 4]
v.castDType.uint32 # 逐通道转换 → SIMD[DType.uint32, 4]

Clamp (method)

钳位(方法)

v.clamp(0.0, 1.0) # element-wise clamp to [lower, upper]
v.clamp(0.0, 1.0) # 逐通道钳位到[lower, upper]

min/max are FREE FUNCTIONS, not methods

min/max是自由函数,而非方法

from std.math import min, max min(a, b) # element-wise min (same-type SIMD args) max(a, b) # element-wise max
from std.math import min, max min(a, b) # 逐通道取最小值(同类型SIMD参数) max(a, b) # 逐通道取最大值

Element-wise ternary via bool SIMD

通过布尔SIMD实现逐通道三元运算

var mask = (v > 0.0) # SIMD[DType.bool, 4] mask.select(true_case, false_case) # picks per-lane
var mask = (v > 0.0) # SIMD[DType.bool, 4] mask.select(true_case, false_case) # 逐通道选择

Reductions

归约操作

v.reduce_add() # horizontal sum → Scalar v.reduce_max() # horizontal max → Scalar v.reduce_min() # horizontal min → Scalar
undefined
v.reduce_add() # 水平求和 → Scalar v.reduce_max() # 水平取最大值 → Scalar v.reduce_min() # 水平取最小值 → Scalar
undefined

Strings

字符串

len(s)
returns byte length, not codepoint count. Mojo strings are UTF-8. Byte indexing requires keyword syntax:
s[byte=idx]
(not
s[idx]
).
mojo
var s = "Hello"
len(s)                  # 5 (bytes)
s.byte_length()         # 5 (same as len)
s.count_codepoints()    # 5 (codepoint count — differs for non-ASCII)
len(s)
返回字节长度,而非码点数量。Mojo字符串是UTF-8编码。字节索引需要使用关键字语法:
s[byte=idx]
(而非
s[idx]
)。
mojo
var s = "Hello"
len(s)                  # 5(字节数)
s.byte_length()         # 5(与len结果相同)
s.count_codepoints()    # 5(码点数量——非ASCII字符时会不同)

Iteration — by codepoint slices (not bytes)

迭代 —— 按码点切片(而非字节)

for cp_slice in s.codepoint_slices(): print(cp_slice)
for cp_slice in s.codepoint_slices(): print(cp_slice)

Codepoint values

码点值

for cp in s.codepoints(): print(Int(cp)) # Codepoint is a Unicode scalar value type
for cp in s.codepoints(): print(Int(cp)) # Codepoint是Unicode标量值类型

StaticString = StringSlice with static origin (zero-allocation)

StaticString = 带静态来源的StringSlice(零分配)

comptime GREETING: StaticString = "Hello, World"
comptime GREETING: StaticString = "Hello, World"

t-strings for interpolation (lazy, type-safe)

使用t-string进行插值(惰性、类型安全)

var msg = t"x={x}, y={y}"
var msg = t"x={x}, y={y}"

String.format() for runtime formatting

使用String.format()进行运行时格式化

var s = "Hello, {}!".format("world")
undefined
var s = "Hello, {}!".format("world")
undefined

Error handling

错误处理

raises
can specify a type.
try
/
except
works like Python:
mojo
def might_fail() raises -> Int:          # raises Error (default)
    raise Error("something went wrong")

def parse(s: String) raises Int -> Int:  # raises specific type
    raise 42

try:
    var x = parse("bad")
except err:                               # err is Int
    print("error code:", err)
No
match
statement. No
async
/
await
— use
Coroutine
/
Task
from
std.runtime
.
raises
可以指定类型。
try
/
except
的工作方式与Python类似:
mojo
def might_fail() raises -> Int:          # 默认抛出Error类型
    raise Error("something went wrong")

def parse(s: String) raises Int -> Int:  # 抛出指定类型
    raise 42

try:
    var x = parse("bad")
except err:                               # err是Int类型
    print("error code:", err)
没有
match
语句。没有
async
/
await
——请使用
std.runtime
中的
Coroutine
/
Task

Function types and closures

函数类型和闭包

No lambda syntax. Closures use
capturing[origins]
:
mojo
undefined
没有lambda语法。闭包使用
capturing[origins]
mojo
undefined

Function type with capture

带捕获的函数类型

comptime MyFunc = fn(Int) capturing[_] -> None
comptime MyFunc = fn(Int) capturing[_] -> None

Parametric function type (for vectorize etc.)

参数化函数类型(用于vectorize等)

comptime SIMDFunc = fnwidth: Int capturing[_] -> None
comptime SIMDFunc = fnwidth: Int capturing[_] -> None

vectorize pattern

vectorize模式

from std.algorithm import vectorize vectorize[simd_width](size, my_closure)
undefined
from std.algorithm import vectorize vectorize[simd_width](size, my_closure)
undefined

Type hierarchy

类型层次

AnyType
  ImplicitlyDestructible          — auto __del__; most types
  Movable                         — __init__(out self, *, deinit take: Self)
    Copyable                      — __init__(out self, *, copy: Self)
      ImplicitlyCopyable(Copyable, ImplicitlyDestructible)
    RegisterPassable(Movable)
      TrivialRegisterPassable(ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable)
AnyType
  ImplicitlyDestructible          —— 自动生成__del__;大多数类型都属于此类
  Movable                         —— 实现__init__(out self, *, deinit take: Self)
    Copyable                      —— 实现__init__(out self, *, copy: Self)
      ImplicitlyCopyable(Copyable, ImplicitlyDestructible)
    RegisterPassable(Movable)
      TrivialRegisterPassable(ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable)