On Sun, Jul 28, 2013 at 11:03 AM, Jonathan S. Shapiro <[email protected]>wrote:

> The second is their lifetime mechanism for non-GC tracked return values.
>
> I'm not following how this relates to borrowed pointers. Can you explain?
>

This blog post I referenced in the other thread does decent job of
explaining it...

   http://tim.dreamwidth.org/1784423.html

However, because that's long and wordy, here is an attempt at a shorter
explanation. Assume a completely "owned pointer" linear-type definition of
an IntLinkedList and this function which uses it... (though mentally
consider the general case for a paramaterized list type)

fn main() {
    let alist = IntLinkedList { head: ~5, tail: Some(~IntList{ head: ~7,
tail: None}) };
    let second_element : int = secondElementOf(alist);
    assert  second_element == 7;
 }

The trouble starts because alist goes out of scope after the second
statement.

This puts us in a funny situation WRT the return value of
secondElementOf(). It is undesirable for it to be a copy of the
list-payload, which could be large. We would prefer to return a
borrowed-pointer to the list-payload. However, doing so requires a
mechanism to assure the list-scope lifetime exceeds the return-value
lifetime.

Rust's solution is explicit lifetimes for borrowed pointers. Basically, the
secondElementOf function can be declared such that the lifetime of the
return value is BOUND to the lifetime of the input parameters -- like this:

fn secondElementOf(alist: &INPUTLIFETIME/IntList) -> &INPUTLIFETIME/int {
... }

This says to the compiler: the borrowed pointer return value is only valid
so long as the entire input parameter which was passed to the function is
still held.

This seems like a neat mechanism for establishing lifetime for
borrowed-pointer return values. As a bonus, the introduction of this
explicit mechanism, and the requirement to use it, means that owned
pointers can be destroyed the instant they go out of scope.

The downsides seem to be that (a) a borrowed return value to the payload of
a single list-element will keep the entire data-structure alive, (b) as far
as I can see, this effectively adds the requirement that the list-pointers
must be immutable, since if they were mutable the lifetime of list-elements
would not equal the lifetime of the head.
_______________________________________________
bitc-dev mailing list
[email protected]
http://www.coyotos.org/mailman/listinfo/bitc-dev

Reply via email to