在 NEAR Rust 智能合约中停止执行的首选方法是什么?

What's the preferred way to stop execution in NEAR Rust smart contracts?

至少有3种方法可以停止程序执行

  1. panic!
  2. assert!(而且都是兄弟姐妹)
  3. env::panic

如何正确停止智能合约的执行?

有什么比较好的方法吗?什么时候应该使用 env::panic?

他们最终都会打电话给 env::panic。来自文档 Terminates the execution of the program with the UTF-8 encoded message.。它是导入到合约的主机函数的包装器。

至于另外两个,assert! 检查一个布尔值并用一条消息调用 panic!。 它们都支持 fmt::Display 特性,这意味着您可以使用“{}”进行字符串插值,标记传递的字符串将按照它们出现的顺序出现在何处。

例如

assert!(b, "{}", "oops");
/// is
if (b) {
  panic!("{}", "oops");
}
/// is equivalent to 
if (b) {
  env::panic(format!("{}", "oops"));
}

因此您可以根据需要使用任何一个。在 near-sdk-rs/examples like the fungible token contract.

中查看示例的好地方