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

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

本文介绍了为什么这两种结构在受寿命影响的方式上有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,它包含对RequestTcpStream的引用,而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.

这篇关于为什么这两种结构在受寿命影响的方式上有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:02