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
已移除语法 —— 请勿生成这些
| Removed | Replacement |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| Not in stdlib (use SIMD, List, UnsafePointer) |
| Still used for nested compile-time closures |
| 已移除语法 | 替代方案 |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 不在标准库中(使用SIMD、List、UnsafePointer) |
嵌套的 | 仍用于嵌套编译时闭包 |
def
is the only function keyword
defdef
是唯一的函数关键字
deffndefraisesraisesmojo
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 during migration. New code should always use .
fndeffndefraisesraisesmojo
def compute(x: Int) -> Int: # 不抛出异常(编译器强制检查)
return x * 2
def load(path: String) raises -> String: # 显式声明抛出异常
return open(path).read()
def main() raises: # main通常会抛出异常 → 使用def raises
...注意:现有标准库代码在迁移期间仍会使用。新代码应始终使用。
fndefcomptime
replaces alias
and @parameter
comptimealias@parametercomptime
替代alias
和@parameter
comptimealias@parametermojo
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 assertioncomptime assertmain()__init__Inside structs, defines associated constants and type aliases:
comptimemojo
struct MyStruct:
comptime DefaultSize = 64
comptime ElementType = Float32mojo
comptime N = 1024 # 编译时常量
comptime MyType = Int # 类型别名
comptime if condition: # 编译时分支
...
comptime for i in range(10): # 编译时循环
...
comptime assert N > 0, "N must be positive" # 编译时断言comptime assertmain()__init__在结构体内部,用于定义关联常量和类型别名:
comptimemojo
struct MyStruct:
comptime DefaultSize = 64
comptime ElementType = Float32Argument conventions
参数约定
Default is (immutable borrow, never written explicitly). The others:
readmojo
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默认是(不可变借用,无需显式编写)。其他类型如下:
readmojo
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
undefinedmojo
undefinedConstructor
构造函数
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复制构造函数(仅关键字参数copy
)
copydef 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移动构造函数(仅关键字参数deinit take
)
deinit takedef 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
undefinedmojo
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 — bare parameter names are errors:
Self.ParamNamemojo
undefined在结构体内部,必须使用——直接使用参数名称会报错:
Self.ParamNamemojo
undefinedWRONG — 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 (e.g., , ) require explicit or ownership transfer :
ImplicitlyCopyableDictList.copy()^mojo
undefined未实现的类型(如、)需要显式调用或使用所有权转移操作符:
ImplicitlyCopyableDictList.copy()^mojo
undefinedWRONG — 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^
undefinedvar result = MyStruct(headers=d.copy()) # 或者:headers=d^
undefinedImports use std.
prefix
std.导入需使用std.
前缀
std.mojo
from std.testing import assert_equal, TestSuite
from std.algorithm import vectorize
from std.python import PythonObject
import std.randomPrelude auto-imports (no import needed): , , , , , , , , , , , , , , , , , , , , , , , , , and more.
IntStringBoolListDictOptionalSIMDFloat32Float64UInt8PointerUnsafePointerSpanErrorDTypeWritableWriterCopyableMovableEquatableHashablerebindprintrangelenrebind[TargetType](value)mojo
from std.testing import assert_equal, TestSuite
from std.algorithm import vectorize
from std.python import PythonObject
import std.random预导入的内容(无需手动导入):、、、、、、、、、、、、、、、、、、、、、、、、等。
IntStringBoolListDictOptionalSIMDFloat32Float64UInt8PointerUnsafePointerSpanErrorDTypeWritableWriterCopyableMovableEquatableHashablerebindprintrangelenrebind[TargetType](value)Writable
/ Writer
(replaces Stringable
)
WritableWriterStringableWritable
/ Writer
(替代Stringable
)
WritableWriterStringablemojo
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- — builtin existential type (not
Some[Writer]directly)Writer - Both methods have default implementations via reflection if all fields are — simple structs need not implement them
Writable - Convert to with
String, notString.write(value)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),而非Stringstr(value)
Iterator protocol
迭代器协议
Iterators use (not ):
raises StopIterationOptionalmojo
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 StopIterationOptionalmojo
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
内存和指针类型
| Type | Use |
|---|---|
| Safe, non-nullable. Deref with |
| Free function |
| Non-owning contiguous view. |
| Unique ownership (like Rust |
| Reference-counted shared ownership. |
UnsafePointeroriginMutExternalOriginArcPointermojo
undefined| 类型 | 用途 |
|---|---|
| 安全、非空指针。使用 |
| 自由函数 |
| 非所有权的连续内存视图。 |
| 唯一所有权(类似Rust的 |
| 引用计数的共享所有权。 |
UnsafePointeroriginMutExternalOriginArcPointermojo
undefinedStruct 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
undefinedfn init(out self, size: Int):
self._ptr = allocSelf.T
undefinedOrigin system (not "lifetime")
来源系统(非“生命周期”)
Mojo tracks reference provenance with origins, not "lifetimes":
mojo
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...Key types: , , , , , , , . Use to get a value's origin.
OriginMutOriginImmutOriginMutAnyOriginImmutAnyOriginMutExternalOriginImmutExternalOriginStaticConstantOriginorigin_of(value)Mojo使用**来源(origin)**而非“生命周期”来跟踪引用的溯源:
mojo
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]: ...关键类型:、、、、、、、。使用获取值的来源。
OriginMutOriginImmutOriginMutAnyOriginImmutAnyOriginMutExternalOriginImmutExternalOriginStaticConstantOriginorigin_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
集合字面量
Listmojo
undefinedListmojo
undefinedWRONG — 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]
undefinedvar 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]
undefinedCommon decorators
常用装饰器
| Decorator | Purpose |
|---|---|
| Generate fieldwise constructor |
| Allow implicit conversion |
| Force inline |
| Prevent inline |
| Static method |
| Deprecation warning |
| Hide from docs |
| Linear type (no implicit destruction) |
| 装饰器 | 用途 |
|---|---|
| 生成基于字段的构造函数 |
| 允许隐式转换 |
| 强制内联 |
| 禁止内联 |
| 静态方法 |
| 发出弃用警告 |
| 在文档中隐藏 |
| 线性类型(无隐式销毁) |
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 → IntLiterals are polymorphic — and auto-adapt to context:
FloatLiteralIntLiteralmojo
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字面量是多态的——和会自动适配上下文:
FloatLiteralIntLiteralmojo
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
undefinedmojo
undefinedConstruction 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
undefinedv.reduce_add() # 水平求和 → Scalar
v.reduce_max() # 水平取最大值 → Scalar
v.reduce_min() # 水平取最小值 → Scalar
undefinedStrings
字符串
len(s)s[byte=idx]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)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")
undefinedvar s = "Hello, {}!".format("world")
undefinedError handling
错误处理
raisestryexceptmojo
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 statement. No / — use / from .
matchasyncawaitCoroutineTaskstd.runtimeraisestryexceptmojo
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)没有语句。没有/——请使用中的/。
matchasyncawaitstd.runtimeCoroutineTaskFunction types and closures
函数类型和闭包
No lambda syntax. Closures use :
capturing[origins]mojo
undefined没有lambda语法。闭包使用:
capturing[origins]mojo
undefinedFunction 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)
undefinedfrom std.algorithm import vectorize
vectorize[simd_width](size, my_closure)
undefinedType 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)