本文针对熟悉 Solidity 的开发者,介绍其常用语法并展示在 Rust 中的对应实现。
本文针对熟悉 Solidity 的开发者,介绍其常用语法并展示在 Rust 中的对应实现。让我们创建一个名为 tryrust 的 Anchor 项目,并逐步探索相关概念。
创建一个新 Anchor 项目:anchor init tryrust,并配置好开发环境。
Solidity 提供两种控制执行流程的方式:if-else 语句和三元运算符。以下是对比它们在 Solidity 和 Rust 中的实现。
在 Solidity 中:
function ageChecker(uint256 age) public pure returns (string memory) {
if (age >= 18) {
return "You are 18 years old or above";
} else {
return "You are below 18 years old";
}
}
在 Rust(Solana 的 lib.rs 中添加以下函数):
pub fn age_checker(ctx: Context<Initialize>, age: u64) -> Result<()> {
if age >= 18 {
msg!("You are 18 years old or above");
} else {
msg!("You are below 18 years old");
}
Ok(())
}
注意:Rust 中 if 条件后的括号是可选的,age >= 18 不需额外括号。
测试代码(在 tests/tryrust.ts 中添加):
it("Age checker", async () => {
const tx = await program.methods.ageChecker(new anchor.BN(35)).rpc();
console.log("Your transaction signature", tx);
});
运行 anchor test 后的日志:
Transaction executed in slot 9:
Signature: 3uB77AcQpxCZPsFu4MaVdpwfGxDRXTmUEEdxDNGD1CnYodY9kcsRjR75pcSkXJs8qLn6gYCsEAPgqz6ovsYJkCBN
Status: Ok
Log Messages:
Program 7gHaAQrPS1TeCoohEu6F8RTC7bBauYVCfvriUdJrao8W invoke [1]
Program log: Instruction: AgeChecker
Program log: You are 18 years old or above
Program 7gHaAQrPS1TeCoohEu6F8RTC7bBauYVCfvriUdJrao8W consumed 340 of 200000 compute units
Program 7gHaAQrPS1TeCoohEu6F8RTC7bBauYVCfvriUdJrao8W success
Solidity 中的三元运算符示例:
function ageChecker(uint256 age) public pure returns (bool a) {
a = age % 2 == 0 ? true : false;
}
Rust 中没有直接的三元运算符,但可以用 if-else 表达式赋值给变量:
pub fn age_checker(ctx: Context<Initialize>, age: u64) -> Result<()> {
let result = if age >= 18 { "You are 18 years old or above" } else { "You are below 18 years old" };
msg!("{:?}", result);
Ok(())
}
注意:
Rust 提供更强大的 match 控制流,类似于增强版的 switch。示例:
pub fn age_checker(ctx: Context<Initialize>, age: u64) -> Result<()> {
match age {
1 => msg!("The age is 1"),
2 | 3 => msg!("The age is either 2 or 3"),
4..=6 => msg!("The age is between 4 and 6"),
_ => msg!("The age is something else"),
}
Ok(())
}
match 支持单值匹配、多值匹配(用 | 分隔)、范围匹配(..= 表示包含边界)和通配符 _。
Solidity 中的 for 循环:
function loopOverSmth() public {
for (uint256 i = 0; i < 10; i++) {
}
}
Rust 中的等价写法:
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
for i in 0..10 {
}
Ok(())
}
Solidity 中步长为 2 的循环:
function loopOverSmth() public {
for (uint256 i = 0; i < 10; i += 2) {
}
}
Rust 中使用 step_by:
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
for i in (0..10).step_by(2) {
msg!("{}", i);
}
Ok(())
}
运行测试后的日志:
Transaction executed in slot 3:
Signature: 3DVe2LzukpWnu2A3HkATFMET7BVd8pA7JTumJ51u7AT615BH5vobbdBsWS4MZfwHo5txk3zFC1mLnDLbMDWGUET6
Status: Ok
Log Messages:
Program log: 0
Program log: 2
Program log: 4
Program log: 6
Program log: 8
Program consumed 2272 of 200000 compute units
Rust 的数组支持与 Solidity 不同。Solidity 内置固定和动态数组,而 Rust 原生支持固定数组,动态长度需使用 Vec。
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let my_array: [u32; 5] = [10, 20, 30, 40, 50];
let first_element = my_array[0];
let third_element = my_array[2];...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!