I reply to my questions. It can be helpful to somebody.
First the error: wrong number of lifetime parameters
The struct encoder is declared pub struct Encoder<'self> so the <'self> lifetime is part of the type and must be keep. The good declaration is pub fn buffer_encode<T:Encodable<Encoder<'self>>>(to_encode_object: &T) -> ~[u8]

The call to the function is : Encoder::buffer_encode(&to_encode_object)

For the other questions.
The lifetime has been added to init (pub fn init<'a>(wr: &'a mut io::Writer) -> Encoder<'a>) because the borrowed specified parameter (wr) is returning in the Encoder and must be keep borrower after the call and during all the Encoder use. Fn Init borrow the wr and give it to the Encoder. After the 'init' call, returned Encoder is use to encode object and wr must still be borrowed. The call to init and encode are put inside a scoped block to manage the Encoder lifetime:
ex:
        let mut m = MemWriter::new();
        {
            let mut encoder = Encoder::init(&mut m as &mut Writer);
            to_encode_object.encode(&mut encoder);
        }
        m.inner()

Why the type is declared with a <'self> lifetime (pub struct Encoder<'self>). It's not so clear. What I think, It's because the struct contains an attribute (priv wr: &'self mut io::Writer) that have a variable lifetime (depend on the use) , so to be configurable the lifetime must be declared as a generic in the struct. The variable lifetime is needed because, it allow the Encoder to borrow the writer during a lifetime longer that the function call (lifetime of normal borrowing) needed in the init function.

For more informations:
http://static.rust-lang.org/doc/master/tutorial-borrowed-ptr.html : to understand borrowing mechanism https://www.mail-archive.com/[email protected]/msg05811.html : for the <'self>

Hope my explication is clear.

I have remark about the list and the thread 'Rust Forum', I think it become important to have a user mailing list or forum. It's the second time I answer to my trivial questions and I fell that I'm annoying everybody with these.

Philippe Delrieu


Le 01/12/2013 18:28, Philippe Delrieu a écrit :
I see the PR has been approved to I try to implements the method 'pub fn buffer_encode<T:Encodable<Encoder>>(to_encode_object: &T) -> ~[u8]' and I have this error : "error: wrong number of lifetime parameters: expected 1 but found 0" and indicate the Encoder type.

I have another question. I try to understand the modification on json.rs and function declaration has changed from :
impl serialize::Encoder for Encoder
to:
impl<'self> serialize::Encoder for Encoder<'self>
or
pub fn init<'a>(wr: &'a mut io::Writer) -> Encoder<'a>
instead of
pub fn new(wr: &mut io::Writer) -> Encoder

Could you explain me the difference if you don't mind.

Philippe

_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to