【发布时间】:2021-12-21 13:33:15
【问题描述】:
我一直在开发一个旨在在 Solana 运行时上运行的程序。我最近遇到了一个问题,数组中的第二项被传递到“test2”中会出现某种生命周期错误。当显式生命周期注释添加到 test1 时,此错误消失,但我无法弄清楚它为什么首先出现。
pub fn test1(
test_account_1: &AccountInfo,
test_account_2: &AccountInfo,
mint_account: &AccountInfo,
) -> ProgramResult {
test2(&[test_account_1.clone(), test_account_2.clone()]);
return Ok(());
}
pub fn test2(arr: &[AccountInfo]) {
for a in arr.iter() {
println!("{}", a.key)
}
}
错误:
寿命不匹配
...但是来自
test_account_1的数据流入test_account_2这里是 rustc (E0623)
lib.rs(207, 22):这两种类型声明为 不同的生命周期...
lib.rs(208, 22):
lib.rs(211, 37): ...但是数据 从
test_account_1流入test_account_2这里
AccountInfo 的定义:
/// Account information
#[derive(Clone)]
pub struct AccountInfo<'a> {
/// Public key of the account
pub key: &'a Pubkey,
/// Was the transaction signed by this account's public key?
pub is_signer: bool,
/// Is the account writable?
pub is_writable: bool,
/// The lamports in the account. Modifiable by programs.
pub lamports: Rc<RefCell<&'a mut u64>>,
/// The data held in this account. Modifiable by programs.
pub data: Rc<RefCell<&'a mut [u8]>>,
/// Program that owns this account
pub owner: &'a Pubkey,
/// This account's data contains a loaded program (and is now read-only)
pub executable: bool,
/// The epoch at which this account will next owe rent
pub rent_epoch: Epoch,
}
【问题讨论】:
-
请提供重现错误的最小示例(例如在online playground 上)。
-
除非您有特殊需要,否则我强烈建议您将
&'a Pubkey字段切换为仅Pubkey并拥有数据,并同样摆脱 RefCells 上的生命周期注释。 (理想情况下,我也会摆脱这些 RefCell。它们非常可疑。将RefCell公开是非常奇怪的 IMO。很难避免程序崩溃。如果您使用对避免复制,您可能会查看std::borrow::Cow。如果您必须在简单的非通用代码上标记很多生命周期,那么您可能走错了 IMO 路径。 -
AccountInfo 结构取自 Solana 库 (github.com/solana-labs/solana/blob/…),我只是想制作一个可重复性最低的示例。很抱歉造成混乱。