将帐户 ID 作为参数传递给 Promise::new() 后的访问值

Access value of account ID after passing it as parameter to Promise::new()

以下代码会产生错误:

let account_id = env::signer_account_id();
let amount = 10 * 1_000_000_000_000_000_000_000_000;
Promise::new(account_id).transfer(amount);
env::log(format!("Sent {} NEAR to {}", amount, account_id).as_bytes());
    |
102 |         let account_id = env::signer_account_id();
    |             ---------- move occurs because `account_id` has type `std::string::String`, which does not implement the `Copy` trait
103 |         let amount = 10 * 1_000_000_000_000_000_000_000_000;
104 |         Promise::new(account_id).transfer(amount);
    |                      ---------- value moved here
105 |         env::log(format!("Sent {} NEAR to {}", amount, account_id).as_bytes());
    |                                                        ^^^^^^^^^^ value borrowed here after move

我可以通过声明另一个变量 same_account_id 来解决这个问题,这似乎是让它工作的一种非常糟糕的方法。

let account_id = env::signer_account_id();
let same_account_id = env::signer_account_id();
let amount = 10 * 1_000_000_000_000_000_000_000_000;
Promise::new(account_id).transfer(amount);
env::log(format!("Sent {} NEAR to {}", amount, same_account_id).as_bytes());

Promise::new() 中作为参数传递后,引用 account_id 的更好/rusty 方法是什么?

String 没有实现 Copy,而 Promise::new() 按值获取其参数。这就是为什么 Rust 说这个值被移动了并且不允许你以后使用它。

解决此问题的最简单方法是使用 Clone::clone():

Promise::new() 一个显式副本
Promise::new(account_id.clone()).transfer(amount);

或者,您可以在将 account_id 提供给 promise 构造函数之前构建格式字符串,因为 format! 宏发出的代码不会取得该字符串的所有权。这可以防止不必要的字符串复制。

let msg = format!("Sent {} NEAR to {}", amount, account_id).as_bytes();
Promise::new(account_id).transfer(amount);
env::log(msg);