Rust/Anchor,借用时丢弃的临时值,请考虑使用"let"绑定来创建寿命更长的值


有人知道如何解决这个问题吗?我试着使用let表达式,但最终出现了一个停顿的问题。。。出现错误的原因是";种子";可变
pub fn exec_payout(ctx: Context<MyInstruction>, amount: u64, bump:u8, p1:Pubkey, p2:Pubkey, rstring:String) -> Result<()> {
let cpi_program = ctx.accounts.system_program.to_account_info();
let cpi_accounts = system_program::Transfer {
from: ctx.accounts.account_a.clone(),
to: ctx.accounts.account_b.clone(),
};
let seeds = [rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), &[bump]].as_slice();
let seedz = &[seeds.clone()];
let cpi_context = CpiContext::new(cpi_program, cpi_accounts)
.with_signer(seedz);
system_program::transfer(cpi_context, amount)?; 
Ok(())
}

我试着这样写,但最终还是出现了同样的错误。。。有人能帮我吗

let cpi_context = CpiContext::new(cpi_program, cpi_accounts)
.with_signer(&[&[rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), &[bump]]]);

我得到的错误

本质上,每次执行&[XYZ]时,都需要将其存储在变量1中,以使其保持活动状态:

let bumps = &[bump];
let seeds = &[rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), bumps][..];
let seedz = &[seeds];

你所有的值都是引用,通常你不能保留临时值的引用,除非的形式为let x = &...,则寿命将自动延长。请参阅此问答;A了解更多细节:为什么借临时工是合法的?执行[XYZ].as_slice()不起作用,如果需要将其强制为切片,而不是简单地引用数组,请在末尾使用[..]

另一种方法是构造切片并同时使用它们,但必须在一个表达式中完成,因为这就是临时值的生存时间。您的上一次尝试没有成功,因为CpiContext也只是引用了值,您还需要使用(通过将其传递给transfer()(:

system_program::transfer(
CpiContext::new_with_signer(
cpi_program,
cpi_accounts,
&[&[rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), &[bump]]],
amount)?; 

1:除非该值可以常量提升

最新更新