Rust 生命周期会影响编译程序的语义吗? [英] Do Rust lifetimes influence the semantics of the compiled program?

查看:37
本文介绍了Rust 生命周期会影响编译程序的语义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 Rust 中的生命周期,并问自己它们是否只是"一种安全措施(以及一种交流如何确保安全的方式,在出现错误的情况下),或者是否存在以下情况生命周期的不同选择实际上会改变程序的运行方式,即生命周期是否对编译后的程序产生语义差异.

I'm trying to grok lifetimes in Rust and asked myself whether they are "just" a safety measure (and a way to communicate how safety is ensured, or not, in the case of errors) or if there are cases where different choices of lifetimes actually change how the program runs, i.e. whether lifetimes make a semantic difference to the compiled program.

对于生命周期",我指的是我们包含的所有讨厌的小 'a'b'static 标记借检查员开心.当然,写

And with "lifetimes" I refer to all the pesky little 'a, 'b, 'static markers we include to make the borrow checker happy. Of course, writing

{
    let foo = File::open("foo.txt")?;
} 
foo.write_all(b"bar");

代替

let foo = File::open("foo.txt")?;
foo.write_all(b"bar");

将在写入发生之前关闭文件描述符,即使我们之后可以访问 foo,但这种作用域和析构函数调用也发生在 C++ 中.

will close the file descriptor before the write occurs, even if we could access foo afterwards, but that kind of scoping and destructor-calling also happens in C++.

推荐答案

不,生命周期不会以任何方式影响生成的机器代码.归根结底,所有只是指向"已编译代码的指针.

No, lifetimes do not affect the generated machine code in any way. At the end of the day, it's all "just pointers" to the compiled code.

因为我们是说人类语言的人类,所以我们倾向于将两个不同但相关的概念混为一谈:具体生命周期通用生命周期参数.

Because we are humans speaking a human language, we tend to lump two different but related concepts together: concrete lifetimes and generic lifetime parameters.

所有编程语言都有具体的生命周期.这仅对应于何时释放资源.这就是您的示例所显示的内容,实际上,C++ 的工作方式与 Rust 在那里的工作方式相同.这通常称为资源获取即初始化 (RAII).垃圾收集语言也有生命周期,但很难确定它们何时结束.

All programming languages have concrete lifetimes. That just corresponds to when a resource will be released. That's what your example shows and indeed, C++ works the same as Rust does there. This is often known as Resource Acquisition Is Initialization (RAII). Garbage-collected languages have lifetimes too, but they can be harder to nail down exactly when they end.

Rust 在这方面的优势在于通用的生命周期参数,我们称之为 'a'static.这些允许编译器跟踪底层指针,这样程序员就不必担心指针是否会保持足够长的有效时间.这适用于在结构中存储引用并将它们传递给函数和从函数传递.

What makes Rust neat in this area are the generic lifetime parameters, the things we know as 'a or 'static. These allow the compiler to track the underlying pointers so that the programmer doesn't need to worry if the pointer will remain valid long enough. This works for storing references in structs and passing them to and from functions.

这篇关于Rust 生命周期会影响编译程序的语义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆