near-smart-contracts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNEAR Smart Contracts Development
NEAR智能合约开发
Comprehensive guide for developing secure and efficient smart contracts on NEAR Protocol using Rust and the NEAR SDK (v5.x).
使用Rust和NEAR SDK(v5.x)在NEAR Protocol上开发安全高效智能合约的综合指南。
When to Apply
适用场景
Reference these guidelines when:
- Writing new NEAR smart contracts in Rust
- Reviewing existing contract code for security and optimization
- Implementing cross-contract calls and callbacks
- Managing contract state and storage
- Testing and deploying NEAR contracts
- Optimizing gas usage and performance
在以下场景中参考本指南:
- 用Rust编写新的NEAR智能合约
- 评审现有合约代码的安全性与优化空间
- 实现跨合约调用及回调
- 管理合约状态与存储
- 测试与部署NEAR合约
- 优化Gas消耗与性能
Getting Started
入门指南
Prerequisites
前置条件
Install the required tools before starting development:
bash
undefined开始开发前安装所需工具:
bash
undefinedInstall Rust (if not already installed)
Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Add wasm32 target for compiling contracts
Add wasm32 target for compiling contracts
rustup target add wasm32-unknown-unknown
rustup target add wasm32-unknown-unknown
Install cargo-near (build, deploy, and manage contracts)
Install cargo-near (build, deploy, and manage contracts)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh
Install near-cli-rs (interact with NEAR network)
Install near-cli-rs (interact with NEAR network)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh
undefinedcurl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh
undefinedCreate a New Project
创建新项目
CRITICAL: ALWAYS runto create new projects. NEVER manually create Cargo.toml, lib.rs, or any project files. The command generates all required files with correct configurations.cargo near new
bash
undefined重要提示:请始终使用创建新项目。切勿手动创建Cargo.toml、lib.rs或任何项目文件。该命令会生成所有配置正确的必要文件。cargo near new
bash
undefinedREQUIRED: Create a new contract project using the official template
REQUIRED: Create a new contract project using the official template
cargo near new my-contract
cargo near new my-contract
Navigate to project directory
Navigate to project directory
cd my-contract
cd my-contract
Build the contract
Build the contract
cargo near build
cargo near build
Run tests
Run tests
cargo test
**Why `cargo near new` is mandatory:**
- Generates correct `Cargo.toml` with proper dependencies and build settings
- Creates proper project structure with `src/lib.rs` template
- Includes integration test setup in `tests/` directory
- Configures release profile with `overflow-checks = true`
- Sets up correct crate-type for WASM compilation
- Avoids common configuration mistakes that cause build failures
**DO NOT:**
- Manually create `Cargo.toml`
- Manually create `src/lib.rs`
- Copy-paste project structure from examples
- Skip this step and create files directlycargo test
**为什么必须使用`cargo near new`:**
- 生成配置正确的`Cargo.toml`,包含合适的依赖项和构建设置
- 创建带有`src/lib.rs`模板的标准项目结构
- 包含`tests/`目录下的集成测试设置
- 配置发布配置文件并启用`overflow-checks = true`
- 设置正确的WASM编译crate类型
- 避免导致构建失败的常见配置错误
**请勿:**
- 手动创建`Cargo.toml`
- 手动创建`src/lib.rs`
- 从示例中复制粘贴项目结构
- 跳过此步骤直接创建文件Project Structure
项目结构
my-contract/
├── Cargo.toml # Dependencies and project config
├── src/
│ └── lib.rs # Main contract code
├── tests/ # Integration tests
│ └── test_basics.rs
└── README.mdmy-contract/
├── Cargo.toml # 依赖项与项目配置
├── src/
│ └── lib.rs # 主合约代码
├── tests/ # 集成测试
│ └── test_basics.rs
└── README.mdDeploy to Testnet
部署到测试网
bash
undefinedbash
undefinedCreate a testnet account (if needed)
Create a testnet account (if needed)
near account create-account sponsor-by-faucet-service my-contract.testnet autogenerate-new-keypair save-to-keychain network-config testnet create
near account create-account sponsor-by-faucet-service my-contract.testnet autogenerate-new-keypair save-to-keychain network-config testnet create
Build in release mode
Build in release mode
cargo near build --release
cargo near build --release
Deploy to testnet
Deploy to testnet
cargo near deploy my-contract.testnet without-init-call network-config testnet sign-with-keychain send
undefinedcargo near deploy my-contract.testnet without-init-call network-config testnet sign-with-keychain send
undefinedRule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Security & Safety | CRITICAL | |
| 2 | Contract Structure | HIGH | |
| 3 | State Management | HIGH | |
| 4 | Cross-Contract Calls | MEDIUM-HIGH | |
| 5 | Contract Upgrades | MEDIUM-HIGH | |
| 6 | Chain Signatures | MEDIUM-HIGH | |
| 7 | Gas Optimization | MEDIUM | |
| 8 | Yield & Resume | MEDIUM | |
| 9 | Testing | MEDIUM | |
| 10 | Best Practices | MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 安全与防护 | 关键 | |
| 2 | 合约结构 | 高 | |
| 3 | 状态管理 | 高 | |
| 4 | 跨合约调用 | 中高 | |
| 5 | 合约升级 | 中高 | |
| 6 | 链签名 | 中高 | |
| 7 | Gas优化 | 中 | |
| 8 | 暂停与恢复 | 中 | |
| 9 | 测试 | 中 | |
| 10 | 最佳实践 | 中 | |
1. Security & Safety (CRITICAL)
1. 安全与防护(关键)
- - Always validate storage operations and check deposits
security-storage-checks - - Implement proper access control using
security-access-controlpredecessor_account_id - - Protect against reentrancy attacks (update state before external calls)
security-reentrancy - - Use
security-overflowin Cargo.toml to prevent overflowoverflow-checks = true - - Validate callback results and handle failures
security-callback-validation - - Mark callbacks as
security-private-callbacksto prevent external calls#[private] - - Validate attached deposits with
security-yoctonear-validationfunctions#[payable] - - Implement minimum deposit checks to prevent spam
security-sybil-resistance
- - 始终验证存储操作并检查押金
security-storage-checks - - 使用
security-access-control实现适当的访问控制predecessor_account_id - - 防止重入攻击(外部调用前更新状态)
security-reentrancy - - 在Cargo.toml中启用
security-overflow以防止溢出overflow-checks = true - - 验证回调结果并处理失败情况
security-callback-validation - - 将回调标记为
security-private-callbacks以防止外部调用#[private] - - 对带有
security-yoctonear-validation注解的函数验证附带的押金#[payable] - - 实施最低押金检查以防止垃圾信息攻击
security-sybil-resistance
2. Contract Structure (HIGH)
2. 合约结构(高)
- - Use
structure-near-bindgenmacro for contract struct (replaces old#[near(contract_state)])#[near_bindgen] - - Implement proper initialization with
structure-initializationpatterns#[init] - - Plan for contract upgrades with versioning mechanisms
structure-versioning - - Use
structure-eventsand structured event logging (NEP-297)env::log_str() - - Follow NEAR Enhancement Proposals (NEPs) for standards
structure-standards - - Use
structure-serializersfor data structs#[near(serializers = [json, borsh])] - - Use
structure-panic-defaultto require initialization#[derive(PanicOnDefault)]
- - 使用
structure-near-bindgen宏定义合约结构体(替代旧版#[near(contract_state)])#[near_bindgen] - - 使用
structure-initialization模式实现正确的初始化逻辑#[init] - - 规划带有版本机制的合约升级方案
structure-versioning - - 使用
structure-events和结构化事件日志(NEP-297)env::log_str() - - 遵循NEAR改进提案(NEPs)中的标准
structure-standards - - 对数据结构体使用
structure-serializers#[near(serializers = [json, borsh])] - - 使用
structure-panic-default强制要求初始化#[derive(PanicOnDefault)]
3. State Management (HIGH)
3. 状态管理(高)
- - Use SDK collections from
state-collections:near_sdk::store,IterableMap,IterableSet,Vector,LookupMap,LookupSet,UnorderedMap,UnorderedSetTreeMap - - Use Borsh for state, JSON for external interfaces
state-serialization - - Use SDK collections for lazy loading to save gas (loaded on-demand, not all at once)
state-lazy-loading - - Implement pagination with
state-paginationand.skip()for large datasets.take() - - Plan state migration strategies using versioning
state-migration - - Remember: 1 NEAR ≈ 100kb storage, contracts pay for their storage
state-storage-cost - - Use unique byte prefixes for all collections (avoid collisions)
state-unique-prefixes - - Native collections (Vec, HashMap) load all data; use only for <100 entries
state-native-vs-sdk
- - 使用
state-collections中的SDK集合:near_sdk::store、IterableMap、IterableSet、Vector、LookupMap、LookupSet、UnorderedMap、UnorderedSetTreeMap - - 状态使用Borsh序列化,外部接口使用JSON
state-serialization - - 使用SDK集合实现懒加载以节省Gas(按需加载,而非一次性全部加载)
state-lazy-loading - - 对大型数据集使用
state-pagination和.skip()实现分页.take() - - 使用版本化规划状态迁移策略
state-migration - - 注意:1 NEAR ≈ 100kb存储,合约需自行支付存储费用
state-storage-cost - - 为所有集合使用唯一字节前缀(避免冲突)
state-unique-prefixes - - 原生集合(Vec、HashMap)会加载所有数据;仅适用于条目数<100的场景
state-native-vs-sdk
4. Cross-Contract Calls (MEDIUM-HIGH)
4. 跨合约调用(中高)
- - Chain promises correctly
xcc-promise-chaining - - Handle all callback scenarios (success, failure)
xcc-callback-handling - - Allocate appropriate gas for cross-contract calls
xcc-gas-management - - Implement robust error handling
xcc-error-handling - - Never unwrap promise results without checks
xcc-result-unwrap
- - 正确链式调用Promise
xcc-promise-chaining - - 处理所有回调场景(成功、失败)
xcc-callback-handling - - 为跨合约调用分配适当的Gas
xcc-gas-management - - 实现健壮的错误处理逻辑
xcc-error-handling - - 切勿在未检查的情况下解包Promise结果
xcc-result-unwrap
5. Contract Upgrades & Migration (MEDIUM-HIGH)
5. 合约升级与迁移(中高)
- - Use enums for state versioning and implement
upgrade-migrationmethod withmigrate#[init(ignore_state)] - - Pattern for contracts that can update themselves programmatically
upgrade-self-update - - Always remove old state structures to free storage
upgrade-cleanup-old-state - - Use multisig or DAO for production upgrade governance
upgrade-dao-controlled
- - 使用枚举进行状态版本化,并使用
upgrade-migration实现#[init(ignore_state)]方法migrate - - 支持合约以编程方式自我更新的模式
upgrade-self-update - - 始终移除旧状态结构以释放存储空间
upgrade-cleanup-old-state - - 生产环境中使用多签或DAO进行升级治理
upgrade-dao-controlled
6. Chain Signatures (MEDIUM-HIGH)
6. 链签名(中高)
- - Derive foreign blockchain addresses, request MPC signatures, and build multichain transactions
chain-signatures - - Handle MPC signature callbacks properly
chain-callback-handling - - Allocate sufficient gas for MPC calls (yield/resume pattern)
chain-gas-allocation
- - 派生外部区块链地址、请求MPC签名并构建多链交易
chain-signatures - - 正确处理MPC签名回调
chain-callback-handling - - 为MPC调用分配足够的Gas(暂停/恢复模式)
chain-gas-allocation
7. Gas Optimization (MEDIUM)
7. Gas优化(中)
- - Batch operations to reduce transaction costs
gas-batch-operations - - Minimize state reads and writes (cache in memory)
gas-minimal-state-reads - - Choose appropriate collection types (LookupMap vs IterableMap)
gas-efficient-collections - - Mark read-only functions as view (
gas-view-functionsin Rust)&self - - Avoid unnecessary cloning of large data structures
gas-avoid-cloning - - Use
gas-early-validationearly to save gas on invalid inputsrequire! - - Attach appropriate gas for cross-contract calls (recommended: 30 TGas)
gas-prepaid-gas
- - 批量操作以降低交易成本
gas-batch-operations - - 最小化状态读写(在内存中缓存)
gas-minimal-state-reads - - 选择合适的集合类型(LookupMap vs IterableMap)
gas-efficient-collections - - 将只读函数标记为view(Rust中使用
gas-view-functions)&self - - 避免对大型数据结构进行不必要的克隆
gas-avoid-cloning - - 尽早使用
gas-early-validation以在无效输入时节省Gasrequire! - - 为跨合约调用附加适当的Gas(推荐:30 TGas)
gas-prepaid-gas
8. Yield & Resume (MEDIUM)
8. 暂停与恢复(中)
- - Create yielded promises, signal resume, handle timeouts, and manage state between yield/resume
yield-resume - - Protect resume methods from unauthorized callers
yield-gatekeeping
- - 创建暂停的Promise、触发恢复、处理超时,并管理暂停/恢复之间的状态
yield-resume - - 保护恢复方法免受未授权调用者的访问
yield-gatekeeping
9. Testing (MEDIUM)
9. 测试(中)
- - Use
testing-integration-tests+near-sandboxfor integration testsnear-api - - Write comprehensive unit tests with mock contexts
testing-unit-tests - - Test with local sandbox environment before testnet/mainnet
testing-sandbox - - Test boundary conditions, overflow, and empty states
testing-edge-cases - - Profile gas usage in integration tests
testing-gas-profiling - - Test cross-contract calls and callbacks thoroughly
testing-cross-contract - - Test promise failures and timeout scenarios
testing-failure-scenarios - - Use
testing-time-travelfor time-sensitive testssandbox.fast_forward()
- - 使用
testing-integration-tests+near-sandbox进行集成测试near-api - - 编写带有模拟上下文的全面单元测试
testing-unit-tests - - 在测试网/主网部署前使用本地沙箱环境测试
testing-sandbox - - 测试边界条件、溢出及空状态
testing-edge-cases - - 在集成测试中分析Gas消耗
testing-gas-profiling - - 全面测试跨合约调用及回调
testing-cross-contract - - 测试Promise失败及超时场景
testing-failure-scenarios - - 使用
testing-time-travel进行时间敏感型测试sandbox.fast_forward()
10. Best Practices (MEDIUM)
10. 最佳实践(中)
- - Use
best-contract-toolsfor NEP standards (FT, NFT, etc.) and NEP-297 structured eventsnear-sdk-contract-tools - - Provide clear, actionable panic messages
best-panic-messages - - Use
best-loggingfor debugging and event emissionenv::log_str() - - Document public methods, parameters, and complex logic
best-documentation - - Define custom error types or use descriptive strings
best-error-types - - Use constants for magic numbers and configuration
best-constants - - Use
best-require-macroinstead ofrequire!for better error messagesassert! - - Return promises from cross-contract calls for proper tracking
best-promise-return - - Reuse SDK-exported crates (borsh, serde, base64, etc.)
best-sdk-crates - - Encode AccountIds in base32 for 40% storage savings
best-account-id-encoding
- - 使用
best-contract-tools实现NEP标准(FT、NFT等)及NEP-297结构化事件near-sdk-contract-tools - - 提供清晰、可操作的panic提示信息
best-panic-messages - - 使用
best-logging进行调试和事件发射env::log_str() - - 为公共方法、参数及复杂逻辑编写文档
best-documentation - - 定义自定义错误类型或使用描述性字符串
best-error-types - - 使用常量替代魔法数字和配置值
best-constants - - 使用
best-require-macro而非require!以获得更好的错误信息assert! - - 从跨合约调用中返回Promise以实现正确追踪
best-promise-return - - 复用SDK导出的crate(borsh、serde、base64等)
best-sdk-crates - - 使用base32编码AccountId以节省40%的存储空间
best-account-id-encoding
How to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/security-storage-checks.md
rules/structure-near-bindgen.md
rules/state-collections.md
rules/xcc-promise-chaining.md
rules/upgrade-migration.md
rules/chain-signatures.md
rules/yield-resume.md
rules/best-contract-tools.md
rules/testing-integration-tests.mdEach rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and NEAR-specific considerations
阅读单个规则文件以获取详细说明和代码示例:
rules/security-storage-checks.md
rules/structure-near-bindgen.md
rules/state-collections.md
rules/xcc-promise-chaining.md
rules/upgrade-migration.md
rules/chain-signatures.md
rules/yield-resume.md
rules/best-contract-tools.md
rules/testing-integration-tests.md每个规则文件包含:
- 规则重要性的简要说明
- 错误代码示例及解释
- 正确代码示例及解释
- 额外背景信息及NEAR特定注意事项
Latest Tools & Versions
最新工具与版本
Development Tools
开发工具
- cargo-near: Latest - Build, deploy, and manage contracts (,
cargo near build)cargo near deploy - near-cli-rs: Latest - Command-line interface for NEAR (,
near contract call)near contract view - rustc: Latest stable - Rust compiler
- near-sandbox: Latest - Local sandbox environment for integration testing
- near-api-rs: Latest - Rust API client for interacting with NEAR (replaces near-workspaces-rs for tests)
- omni-transaction-rs: Latest - Build transactions for multiple blockchains (Bitcoin, Ethereum, etc.)
- cargo-near:最新版本 - 构建、部署及管理合约(、
cargo near build)cargo near deploy - near-cli-rs:最新版本 - NEAR命令行界面(、
near contract call)near contract view - rustc:最新稳定版 - Rust编译器
- near-sandbox:最新版本 - 用于集成测试的本地沙箱环境
- near-api-rs:最新版本 - 用于与NEAR交互的Rust API客户端(替代测试用的near-workspaces-rs)
- omni-transaction-rs:最新版本 - 为多链(比特币、以太坊等)构建交易
SDK Versions
SDK版本
- near-sdk-rs: v5.x (v6.x coming with structured errors support)
- near-sdk-contract-tools: Latest - Derive macros for NEP standards (FT, NFT, Storage Management)
- near-sdk-rs:v5.x(v6.x即将发布,支持结构化错误)
- near-sdk-contract-tools:最新版本 - 用于NEP标准(FT、NFT、存储管理)的派生宏
Key Features
核心特性
- Unified macro syntax: replaces
#[near(contract_state)]+ derives#[near_bindgen] - Flexible serialization: for data structs
#[near(serializers = [json, borsh])] - Store collections: ,
near_sdk::store::IterableMap,IterableSet,LookupMap,LookupSet,Vector,UnorderedMap,UnorderedSetTreeMap - Simplified cross-contract calls: High-level promise API with and
Promise::new().then() - Built-in NEP support: FT (NEP-141), NFT (NEP-171), and other standards
- Result handling: for methods returning
#[handle_result]without panickingResult<T, E> - Yield/Resume: Contracts can yield execution and wait for external services to resume
- Chain Signatures: Sign transactions for other blockchains (Bitcoin, Ethereum, Solana, etc.)
- Contract Tools: Derive macros for Owner, Pause, Role-based access control patterns
- 统一宏语法:替代
#[near(contract_state)]+派生注解#[near_bindgen] - 灵活序列化:对数据结构体使用
#[near(serializers = [json, borsh])] - 存储集合:、
near_sdk::store::IterableMap、IterableSet、LookupMap、LookupSet、Vector、UnorderedMap、UnorderedSetTreeMap - 简化跨合约调用:使用和
Promise::new()的高级Promise API.then() - 内置NEP支持:FT(NEP-141)、NFT(NEP-171)及其他标准
- 结果处理:用于返回
#[handle_result]的方法,避免panicResult<T, E> - 暂停/恢复:合约可暂停执行并等待外部服务恢复
- 链签名:为其他区块链(比特币、以太坊、Solana等)签署交易
- 合约工具:用于所有者、暂停、基于角色的访问控制模式的派生宏
Resources
资源链接
- NEAR Documentation: https://docs.near.org
- Smart Contract Quickstart: https://docs.near.org/smart-contracts/quickstart
- Contract Anatomy: https://docs.near.org/smart-contracts/anatomy/
- NEAR SDK Rust: https://docs.near.org/tools/sdk
- SDK Rust Reference: https://docs.rs/near-sdk
- Storage & Collections: https://docs.near.org/smart-contracts/anatomy/collections
- Best Practices: https://docs.near.org/smart-contracts/anatomy/best-practices
- Cross-Contract Calls: https://docs.near.org/smart-contracts/anatomy/crosscontract
- Yield & Resume: https://docs.near.org/smart-contracts/anatomy/yield-resume
- Contract Upgrades: https://docs.near.org/smart-contracts/release/upgrade
- Chain Signatures: https://docs.near.org/chain-abstraction/chain-signatures
- Chain Signatures Implementation: https://docs.near.org/chain-abstraction/chain-signatures/implementation
- Security Best Practices: https://docs.near.org/smart-contracts/security/welcome
- Integration Testing: https://docs.near.org/smart-contracts/testing/integration-test
- NEP-297 Events: https://github.com/near/NEPs/blob/master/neps/nep-0297.md
- NEAR Standards (NEPs): https://github.com/near/NEPs
- NEAR Examples: https://github.com/near-examples
- Sandbox Testing: https://github.com/near/near-sandbox
- NEAR API Rust: https://github.com/near/near-api-rs
- Omni Transaction RS: https://github.com/near/omni-transaction-rs
- Contract Tools: https://github.com/near/near-sdk-contract-tools
- NEAR官方文档:https://docs.near.org
- 智能合约快速入门:https://docs.near.org/smart-contracts/quickstart
- 合约结构解析:https://docs.near.org/smart-contracts/anatomy/
- NEAR SDK Rust文档:https://docs.near.org/tools/sdk
- SDK Rust参考文档:https://docs.rs/near-sdk
- 存储与集合:https://docs.near.org/smart-contracts/anatomy/collections
- 最佳实践:https://docs.near.org/smart-contracts/anatomy/best-practices
- 跨合约调用:https://docs.near.org/smart-contracts/anatomy/crosscontract
- 暂停与恢复:https://docs.near.org/smart-contracts/anatomy/yield-resume
- 合约升级:https://docs.near.org/smart-contracts/release/upgrade
- 链签名:https://docs.near.org/chain-abstraction/chain-signatures
- 链签名实现:https://docs.near.org/chain-abstraction/chain-signatures/implementation
- 安全最佳实践:https://docs.near.org/smart-contracts/security/welcome
- 集成测试:https://docs.near.org/smart-contracts/testing/integration-test
- NEP-297事件:https://github.com/near/NEPs/blob/master/neps/nep-0297.md
- NEAR标准(NEPs):https://github.com/near/NEPs
- NEAR示例:https://github.com/near-examples
- 沙箱测试:https://github.com/near/near-sandbox
- NEAR API Rust:https://github.com/near/near-api-rs
- Omni Transaction RS:https://github.com/near/omni-transaction-rs
- 合约工具:https://github.com/near/near-sdk-contract-tools
Storage Costs Reference
存储成本参考
| Storage | Cost | Notes |
|---|---|---|
| 1 byte | 0.00001 NEAR | ~10kb per 0.1 NEAR |
| 100 KB | ~1 NEAR | Approximate reference |
| AccountId | 64+ bytes | Can save 40% with base32 encoding |
| Contract code | Variable | Paid by contract account |
| 存储资源 | 成本 | 说明 |
|---|---|---|
| 1字节 | 0.00001 NEAR | 约0.1 NEAR可存储10kb数据 |
| 100 KB | ~1 NEAR | 近似参考值 |
| AccountId | 64+字节 | 使用base32编码可节省40%空间 |
| 合约代码 | 可变 | 由合约账户支付费用 |
SDK Collections Reference
SDK集合参考
| Collection | Iterable | Clear | Ordered | Range | Use Case |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Ordered list with index access |
| No | No | No | No | Fast key-value, no iteration needed |
| No | No | No | No | Fast membership checks |
| Yes | Yes | Yes | No | Key-value with iteration |
| Yes | Yes | Yes | No | Set with iteration |
| Yes | Yes | No | No | Key-value, unordered iteration |
| Yes | Yes | No | No | Set, unordered iteration |
| Yes | Yes | Yes | Yes | Sorted key-value with range queries |
| 集合类型 | 可迭代 | 可清空 | 有序 | 支持范围查询 | 适用场景 |
|---|---|---|---|---|---|
| 是 | 是 | 是 | 是 | 带索引访问的有序列表 |
| 否 | 否 | 否 | 否 | 快速键值对,无需迭代 |
| 否 | 否 | 否 | 否 | 快速成员检查 |
| 是 | 是 | 是 | 否 | 支持迭代的键值对 |
| 是 | 是 | 是 | 否 | 支持迭代的集合 |
| 是 | 是 | 否 | 否 | 键值对,无序迭代 |
| 是 | 是 | 否 | 否 | 集合,无序迭代 |
| 是 | 是 | 是 | 是 | 支持范围查询的有序键值对 |