简体   繁体   English

Rust/Anchor,借用时临时值下降考虑使用 `let` 绑定来创建更长寿命的值

[英]Rust/Anchor, temporary value dropped while borrowed consider using a `let` binding to create a longer lived value

does anyone know how to fix this please?有人知道如何解决这个问题吗? I tried using a let expression but it ended up in a halting problem... The error ocucrs because of the "seeds" variable我尝试使用 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(())
}

I tried writing it like this but it ended up into the same error... can someone help me please我试过这样写,但最终还是出现了同样的错误……有人可以帮我吗

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

the error i get我得到的错误

Essentially, each time you do &[XYZ] it needs to be stored in a variable 1 so that it stays alive:本质上,每次执行&[XYZ]时,都需要将其存储在变量1中,以便它保持活动状态:

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

All your values are references and normally you can't keep around the reference of a temporary value... unless it is in the form let x = &... and then the lifetime will be automatically extended for you.您所有的值都是引用,通常您不能保留临时值的引用...除非它采用let x = &...的形式,然后生命周期将自动为您延长。 See this Q&A for more details: Why is it legal to borrow a temporary?有关更多详细信息,请参阅此问答:为什么借用临时工是合法的? Doing [XYZ].as_slice() doesn't work, use [..] at the end if you need to coerce it into a slice instead of simply a reference to an array.执行[XYZ].as_slice()不起作用,如果您需要将其强制转换为切片而不是简单地引用数组,请在末尾使用[..]

Another route would be to construct your slices and use them all at once, but it must be done in a single expression since that's how long temporary values live.另一种方法是构建切片并一次性使用它们,但必须在单个表达式中完成,因为这是临时值的生存时间。 Your last attempt didn't work since CpiContext also just references the values, you'd need to use it as well (by passing it to transfer() ):您的最后一次尝试没有奏效,因为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: unless the value can be const-promoted 1:除非该值可以被 const 提升

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM