这里是我学习 Web3 开发的个人笔记与心得分享
Personal notes and insights on my Web3 development journey
内存安全、高性能、现代系统编程语言
Rust 是一门赋予每个人构建可靠且高效软件能力的系统编程语言。它在保证性能的同时,通过所有权(Ownership)系统在编译期防止内存错误。
Rust is a systems programming language that empowers everyone to build reliable and efficient software. It guarantees performance while preventing memory errors at compile time through the Ownership system.
零成本抽象,无垃圾回收,像 C/C++ 一样快
编译期保证,杜绝空指针、数据竞争等问题
Cargo 包管理器,优秀的文档和 IDE 支持
支持 Windows、Linux、macOS、WebAssembly
💡 这是 Rust 最独特的特性,也是学习曲线最陡峭的部分 | This is Rust's most unique feature and the steepest part of the learning curve
// 所有权示例 | Ownership Example
{
let s = String::from("hello"); // s 是所有者 | s is the owner
// s 在这里有效 | s is valid here
} // s 离开作用域并被丢弃 | s goes out of scope and is dropped
借用允许你使用值而不获取所有权。有两种引用类型:
&T - 不可变引用(可以同时有多个)&mut T - 可变引用(同一时间只能有一个)// 借用示例 | Borrowing Example
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1); // 借用 | borrow
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
} // s 离开作用域,但因为没有所有权,所以不丢弃 | s goes out of scope but nothing happens
生命周期确保引用始终有效。编译器会验证所有引用都是有效的。
// 生命周期示例 | Lifetime Example
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
| 特性 | Feature | Rust 优势 | Advantage |
|---|---|
| 安全性 | Security | 编译期防止内存漏洞,智能合约更安全 |
| 性能 | Performance | 无 GC,确定性执行,适合区块链 |
| 并发 | Concurrency | Fearless concurrency,处理高吞吐量 |
| 互操作性 | Interoperability | 编译到 WASM,支持多链部署 |
# macOS / Linux
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Windows
# 下载并运行 rustup-init.exe
# Download and run rustup-init.exe from https://rustup.rs/
cargo new my-project
cd my-project
cargo run
高性能 Layer 1 区块链,使用 Rust 构建智能合约
Solana 是一个高性能的 Layer 1 区块链,专注于可扩展性和速度。它使用 Proof of History (PoH) 共识机制,可以达到每秒数万笔交易(TPS)。
Solana is a high-performance Layer 1 blockchain focused on scalability and speed. It uses the Proof of History (PoH) consensus mechanism to achieve tens of thousands of transactions per second (TPS).
65,000+ TPS,毫秒级确认
平均交易费用低于 $0.001
创新共识机制,无需时间戳协调
Sealevel 运行时支持智能合约并行执行
💡 Solana 上的智能合约叫做"程序"(Programs)| Smart contracts on Solana are called "Programs"
Solana 的所有数据存储在账户中。每个账户有唯一的地址和余额。
Solana 的智能合约,使用 Rust 或 C 编写,编译为 BPF 字节码。
调用程序函数的基本单位,包含程序 ID 和账户列表。
可以包含多个指令,原子性执行(全部成功或全部失败)。
// 使用 Anchor 框架的简单计数器程序 | Simple counter program using Anchor
use anchor_lang::prelude::*;
declare_id!("YourProgramIDHere");
#[program]
pub mod counter {
use super::*;
pub fn initialize(ctx: Context) -> Result<()> {
let counter = &mut ctx.accounts.counter;
counter.count = 0;
msg!("Counter initialized! Count: {}", counter.count);
Ok(())
}
pub fn increment(ctx: Context) -> Result<()> {
let counter = &mut ctx.accounts.counter;
msg!("Previous count: {}", counter.count);
counter.count += 1;
msg!("Current count: {}", counter.count);
Ok(())
}
}
#[account]
pub struct Counter {
pub count: u64,
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(
init,
payer = user,
space = 8 + Counter::SPACE
)]
pub counter: Account<'info, Counter>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(mut)]
pub counter: Account<'info, Counter>,
}
sh -c "$(curl -sSfL https://release.solana.com/stable/install)"
# 验证安装 | Verify installation
solana --version
cargo install --git https://github.com/coral-xyz/anchor avm --locked --force
avm install latest
avm use latest
anchor init my-solana-app
cd my-solana-app
anchor build
anchor deploy
以太坊 Layer 2 扩展解决方案,支持 Rust 智能合约
Arbitrum 是以太坊的 Layer 2 扩展解决方案,使用 Optimistic Rollup 技术提供高吞吐量和低交易成本,同时继承以太坊的安全性。
Arbitrum is an Ethereum Layer 2 scaling solution using Optimistic Rollup technology to provide high throughput and low transaction costs while inheriting Ethereum's security.
40,000+ TPS,快速确认
比以太坊主网低 90-95%
完全兼容以太坊工具和 DApp
支持 Rust、C、C++ 编写合约
💡 Stylus 允许开发者使用 Rust、C、C++ 编写智能合约,同时保持完全的 EVM 兼容性!| Stylus allows developers to write smart contracts in Rust, C, C++ while maintaining full EVM compatibility!
Arbitrum Orbit 允许任何人部署专属的 L3 链,并完全支持 Stylus!
// Stylus Rust 智能合约示例 | Stylus Rust Smart Contract Example
use stylus_sdk::prelude::*;
// 定义存储状态 | Define storage state
sol_storage! {
#[entrypoint]
pub struct Counter {
uint256 count;
}
}
// 定义外部接口 | Define external interface
#[external]
impl Counter {
// 构造函数 | Constructor
pub fn init(&mut self) {
self.count.set(U256::from(0));
}
// 获取当前计数 | Get current count
pub fn count(&self) -> U256 {
self.count.get()
}
// 增加计数 | Increment count
pub fn increment(&mut self) {
let current = self.count.get();
self.count.set(current + U256::from(1));
}
// 设置计数 | Set count
pub fn set(&mut self, value: U256) {
self.count.set(value);
}
}
# 使用 Cargo 安装 | Install with Cargo
cargo install --force stylus-cli
# 或使用 cargo-stylus | Or use cargo-stylus
cargo install cargo-stylus
cargo stylus new --stylus my-contract
cd my-contract
# 构建合约 | Build contract
cargo stylus build
# 部署到 Arbitrum 测试网 | Deploy to Arbitrum testnet
cargo stylus deploy \
--rpc-url https://stylus-testnet.arbitrum.io \
--private-key YOUR_PRIVATE_KEY
| 特性 | Feature | Solana | Arbitrum |
|---|---|---|
| 类型 | Type | Layer 1 独立链 | 以太坊 Layer 2 |
| 共识 | Consensus | Proof of History + PoS | Optimistic Rollup |
| 编程语言 | Languages | Rust, C | Solidity, Rust (Stylus), C, C++ |
| TPS | 65,000+ | 40,000+ |
| 交易费用 | Fees | ~$0.00025 | 比 ETH 低 90-95% |
| 确认时间 | Finality | ~400ms | ~1秒 |
| EVM 兼容 | EVM Compatible | 否 (通过 Neon EVM) | 是 |
从零到精通的建议学习顺序
掌握 Rust 语言基础:所有权、借用、生命周期、错误处理
根据兴趣选择 Solana 或 Arbitrum 开始 Web3 开发
构建完整的去中心化应用