简体   繁体   English

在特征实现中声明时,生命周期引用是什么?

[英]What does a lifetime reference when declared in a trait implementation?

I'm learning about named lifetimes in Rust, and I'm having trouble understanding what they represent when they are used in the implementation of a trait. 我正在学习Rust中的命名生命周期,而且当他们用于实现特征时,我很难理解它们代表什么。 Specifically, I'm having trouble understanding this piece of code from libserialize/hex.rs . 具体来说,我无法理解libserialize / hex.rs中的这段代码。 I've removed some comments for brevity's sake. 为简洁起见,我删除了一些评论。

pub trait ToHex {
    fn to_hex(&self) -> ~str;
}

static CHARS: &'static[u8] = bytes!("0123456789abcdef");

impl<'a> ToHex for &'a [u8] {
    fn to_hex(&self) -> ~str {
        let mut v = slice::with_capacity(self.len() * 2);
        for &byte in self.iter() {
            v.push(CHARS[(byte >> 4) as uint]);
            v.push(CHARS[(byte & 0xf) as uint]);
        }

        unsafe {
             str::raw::from_utf8_owned(v)
        }
    }
}

I understand the 'static lifetime in the CHARS definition, but I'm stumped on the lifetime defined in the ToHex implementation. 我理解CHARS定义中的'static生命周期,但我对ToHex实现中定义的生命周期感到困惑。 What do named lifetimes represent in the implementation of a trait? 在生成特征时,命名生命周期代表什么?

In that particular case—not much. 在那个特殊情况下 - 并不多。 &[u8] is not a completely specified type because the lifetime is missing, and implementations must be for fully specified types. &[u8]不是完全指定的类型,因为缺少生命周期,并且实现必须是完全指定的类型。 Thus, the implementation is parameterised over the arbitrary (for the generic parameter is unconstrained) lifetime 'a . 因此,实现是针对任意(对于通用参数是无约束的)生命周期'a参数化'a

In this case, you don't use it again. 在这种情况下,您不要再使用它。 There are cases where you will, however—when you wish to constrain a function argument or return value to the same lifetime. 但是,在某些情况下,当您希望约束函数参数或将值返回到同一生命周期时。

You can then write things like this: 然后你可以这样写:

impl<'a, T> ImmutableVector<'a, T> for &'a [T] {
    fn head(&self) -> Option<&'a T> {
        if self.len() == 0 { None } else { Some(&self[0]) }
    }
    …
}

That means that the return value will have the same lifetime as self , 'a . 这意味着返回值将具有与self相同的生命周期, 'a

Incidentally, just to mess things up, the lifetime could be written manually on each function: 顺便说一句,只是为了弄乱, 可以在每个函数上手动编写生命周期:

impl<'a, T> ImmutableVector<'a, T> for &'a [T] {
    fn head<'a>(&'a self) -> Option<&'a T> {
        if self.len() == 0 { None } else { Some(&self[0]) }
    }
    …
}

… and that demonstrates that having to specify the lifetime of the type that you are implementing for is just so that the type is indeed fully specified. ...这表明必须指定要实现的类型的生命周期才能确保完全指定类型。 And it allows you to write a little bit less for all the functions inside that use that lifetime. 它允许你为使用该生命周期内的所有函数写一点点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM