Struct 值不为';当被置于结构中时,你活得不够长
我正在尝试在Rust中使用LLVM。我试图创建一个代码生成器结构来保存上下文、模块和构建器,但当我尝试编译时,会收到一条错误消息,上面说Struct 值不为';当被置于结构中时,你活得不够长,struct,rust,lifetime,Struct,Rust,Lifetime,我正在尝试在Rust中使用LLVM。我试图创建一个代码生成器结构来保存上下文、模块和构建器,但当我尝试编译时,会收到一条错误消息,上面说c的寿命不够长。我怎样才能编译它,为什么c的寿命不够长 代码: 使用llvm::*; 使用llvm::Attribute::*; pub struct CodeGen, 模块:CSemiBox CodeGen{ 设c=Context::new(); 设b=Builder::new(&c); 设m=Module::new(“test”、&c); 编码基因{ 背景:
c的寿命不够长
。我怎样才能编译它,为什么c的寿命不够长
代码:
使用llvm::*;
使用llvm::Attribute::*;
pub struct CodeGen,
模块:CSemiBox CodeGen{
设c=Context::new();
设b=Builder::new(&c);
设m=Module::new(“test”、&c);
编码基因{
背景:c,
建筑商:b,
模块:m,
}
}
}
完整错误消息:
error: `c` does not live long enough
--> src/codegen.rs:17:31
|
17 | let b = Builder::new(&c);
| ^ does not live long enough
...
24 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'l as defined on the body at 15:32...
--> src/codegen.rs:15:33
|
15 | pub fn new() -> CodeGen<'l> {
| ^
error: `c` does not live long enough
--> src/codegen.rs:18:38
|
18 | let m = Module::new("test", &c);
| ^ does not live long enough
...
24 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'l as defined on the body at 15:32...
--> src/codegen.rs:15:33
|
15 | pub fn new() -> CodeGen<'l> {
| ^
error: aborting due to 2 previous errors
错误:`c`寿命不够长
-->src/codegen.rs:17:31
|
17 |设b=Builder::new(&c);
|^活得不够长
...
24 | }
|-借来的价值仅在此处有效
|
注意:借用值必须在正文15:32定义的生命周期“l”内有效。。。
-->src/codegen.rs:15:33
|
15 | pub fn new()->CodeGen src/CodeGen.rs:15:33
|
15 | pub fn new()->CodeGen这看起来像是一种终身省略让事情变得不那么清晰的情况
以下是Builder::new
:
pub fn new(context: &Context) -> CSemiBox<Builder>
据我所知,当函数的输出类型(在本例中为Builder::new
)具有生存期参数时,如果只有一个输入生存期,则可以省略它。(中和中描述了生存期省略规则。)在这种情况下,输出生存期与输入生存期相同。这意味着之前的原型实际上等同于以下内容:
pub fn new<'a>(context: &'a Context) -> CSemiBox<'a, Builder>
@弗朗西斯加涅啊哈!那是我想链接的,但我只能通过搜索找到。谢谢你的回答!我想我不会使用结构,而是让调用代码创建上下文、模块和生成器,然后将它们传递给代码生成器函数。@trentcl这是或的副本吗?@Shepmaster实际上,我认为这个答案的关键是意识到'a
已经被省略了。但我想我确实讲了更多的细节,其中一些是多余的。为什么要投否决票?
pub struct CSemiBox<'a, D>
pub fn new<'a>(context: &'a Context) -> CSemiBox<'a, Builder>
pub struct CodeGen {
context: CBox<Context>,
builder: CSemiBox<'static, Builder>,
module: CSemiBox<'static, Module>,
}
impl CodeGen {
pub fn new() -> CodeGen {
let c = Context::new(); // returns a CBox<Context>
let c_static_ref: &'static _ = unsafe {
let c_ptr = c.as_ptr() as *const _; // get the underlying heap pointer
&*c_ptr
};
let b = Builder::new(c_static_ref);
let m = Module::new("test", c_static_ref);
CodeGen {
context: c,
builder: b,
module: m,
}
}
}