为什么这两种结构在受寿命影响的方式上有所不同

编程入门 行业动态 更新时间:2024-10-17 15:28:00
本文介绍了为什么这两种结构在受寿命影响的方式上有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是针对以下问题的后续问题:如何解决:无法为自动强制推断合适的寿命.

This is a follow up question to: How to fix: cannot infer an appropriate lifetime for automatic coercion.

我想知道这两种结构为何受寿命影响的方式不同.

I wonder why do these both structs differ in the way they are affected by lifetimes.

示例1

use http; pub struct Request<'a> { pub origin: &'a http::server::Request, }

示例2

use http; pub struct Response<'a, 'b> { pub origin: &'a mut http::server::ResponseWriter<'b>, }

它们看起来与我非常相似,除了第二个引用具有可变的引用,而第一个引用具有不变的引用.

They look pretty much similar to me except that the second one holds a mutable reference whereas the first one holds an immutable reference.

但是,对于示例2 ,我不能仅使用生存期作为参考.我也必须给出该结构的生命期.

However, for Example 2 I can't just use a lifetime for the reference. I must give a lifetime for the struct as well.

所以,我想知道结构中是否有 导致这种行为,或者确实是因为第二个示例中的那个是可变的引用.如果是这样,为什么会导致这种情况.

So, I wonder is there something inside the struct that causes such behavior or is it really because the one in the second example is a mutable reference. And if so, why exactly does that cause that.

推荐答案

&'a T表示您引用了在整个生命周期内有效的T对象.

&'a T means that you have a reference to a T object which is valid for the lifetime'a.

T<'b>表示T对象,其中包含一个在其内部有效期为'b的对象,如struct T<'b> { t: &'b U }中一样.

T<'b> means a T object containing an object inside itself valid for the lifetime 'b, as in struct T<'b> { t: &'b U }.

&'a T<'b>是对T<'b>对象具有生存期'a的引用.

&'a T<'b>is thus a reference with lifetime 'a to a T<'b> object.

对于ResponseWriter,它包含对Request和TcpStream的引用,而Request不包含任何引用.

In the case of the ResponseWriter, it contains references to the Request and to the TcpStream, whereas the Request does not contain any references.

更多推荐

为什么这两种结构在受寿命影响的方式上有所不同

本文发布于:2023-07-19 08:46:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154848.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有所不同   这两种   寿命   结构   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!