Ok, color me confused... perhaps there's somewhere that explains 'self on
more detail? For example, _why_ does the example below not work without the
explicit <'self>? It seems like it should.

I have yet to truly understand the whole 'self thing. When I first read
about lifetimes, my naive expectations were that:

- Every struct has a 'self lifetime, which is basically "as long as this
struct exists". It doesn't matter if I have a @ of the struct or a ~ of the
struct or just a local variable with the struct... when the struct is
dropped, the lifetime ends.

- It follows there's no need to ever annotate structs as generic with a
<'self> parameter - it always exists.

- Any & in a struct is either &'self or &'static. A simple & should be
&'self as that makes more sense (but if Rust wants me to be explicit, fine).

This were my "least surprise" expectations, but things don't work this
way... the problem is I don't have a simple mental model to replace the
above with, so I struggle. What _is_ 'self, exactly?

Isn't a function fn foo(&self) -> &T the same as returning a &'self T? Why
would I want to say fn foo<'a>(&'a self) in the 1st place - 'a is "by
definition" the same as 'self? How come David's Foo example fails the
borrow check?

Besides failing (my) "least surprise" expectations, the current rules also
seem to be a "leaky abstraction". If I have a struct that holds a ComplexT
member, it needs no <'self> parameter. If I then add a private member to my
struct to hold some &'self PartOfT (say, cached access to an internal
member), then boom, all uses of my struct now have to say <'self>, I can no
longer put it in thread-local-storage, etc. I'd expect keeping these sort
of cached borrowed pointers should be an internal implementation detail
which does not affect the users of the struct at all.

I suppose there's a good reason for all this, and a reasonable mental model
I need to put in my head, but digging around the docs I didn't find one...
Any hints would be appreciated :-)


On Sun, Sep 29, 2013 at 5:42 PM, David Renshaw <dwrens...@gmail.com> wrote:

> Cool! I think that solution is much better than mine.
>
> > But I
> > think that polluting traits-interfaces with lifetime annotation is
> > wrong. Why the trait should have lifetime annotation? It is
> > implementation detail.
>
> Just in case you want to see a case where it *does* make sense to put
> a 'self lifetime in a trait definition, here is an example:
>
> https://gist.github.com/dwrensha/db919b8e130e9eb72f0f
> _______________________________________________
> Rust-dev mailing list
> Rust-dev@mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
>
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to