Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

生命周期一章的建议 #1255

Open
xzbdmw opened this issue Jul 24, 2023 · 1 comment
Open

生命周期一章的建议 #1255

xzbdmw opened this issue Jul 24, 2023 · 1 comment

Comments

@xzbdmw
Copy link

xzbdmw commented Jul 24, 2023

因为我半年前是看这个教程入门的(有些概念当初并看不懂),经过半年的学习和实践Rust有一些更好帮助初学者的建议.

  1. 原文中

    当把具体的引用传给 longest 时,那生命周期 'a 的大小就是 x 和 y 的作用域的重合部分,换句话说,'a 的大小将等于 x 和 y 中较小的那个。由于返回值的生命周期也被标记为 'a,因此返回值的生命周期也是 x 和 y 中作用域较小的那个。"

    此处可以加一句说明生命周期在函数参数中只能缩小不能扩大(covariance),因为两个参数的生命周期都是'a,所以'a只能缩小为较小的那个.直接给出这个结论可能让人摸不着头脑.

  2. o生命周期标注并不会改变任何引用的实际作用域 -- 鲁迅
    实在遇到解决不了的生命周期标注问题,可以尝试 T: 'static,有时候它会给你奇迹

    这两句当初让我困惑了很久,既然无法改变真正生命周期又何来什么奇迹,个人觉得这句话有问题,因为T:'static更多用来作为bound而不是讨好编译器,例如tokio::spawn的’static trait bound还有Box<dyn Error + Send + Sync + ‘static>,这里的’static是为了让这个Error全局有效并且可以方便的在在线程间传递,本质还是因为用到的库标了这个bound需要配合,而不是“遇到解决不了的生命周期标注问题”

@xzbdmw
Copy link
Author

xzbdmw commented Jul 24, 2023

另外生命周期标注是取悦编译器这句话个人觉得并不妥当,会让新手觉得这个标注完全是个累赘(是编译器不够聪明的结果),实际上函数参数的生命周期标注不仅可以让编译器知道入参和出参的关系,对于人类阅读代码理解引用的相互关系也有帮助,例如crossbeam的epoch-based gc算法就利用了生命周期标注的Guard来确保引用在多个线程访问下何时有效何时失效来进行高效的垃圾清除

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant