[rust-dev] Converting ~[T] embedded in struct to &[T]

Ashish Myles marcianx at gmail.com
Sat Jan 18 19:47:51 PST 2014


I understand as per a previous discussion that the owned box ~[T] doesn't
quite have the semantics of a unique *pointer*. Below include my successes
in some borrowing scenarios and analogous failed attempts at borrowing a
reference to a unique pointer to an array within a FooVec struct.  How do I
do this?  Is there a borrow() type function/method provided for owned boxes
somewhere? (I see some borrow() stuff within the libstd source, but doesn't
seem to be relevant.)

--------------------------------------------------
fn main() {
    let a : ~[int] = ~[1,2,3];

    // WORKS (borrow1 style below)
    let b : &[int] = a;
}


fn do_borrow<'a, T>(t : &'a T) -> &'a T {
    t
}


struct Foo(~int);

impl Foo {
    fn borrow1<'a>(&'a self) -> &'a int {
        match (self) {
            // error: mismatched types: expected `&'a int` but found `~int`
            // (expected &-ptr but found ~-ptr)
            &Foo(ref v) => *v
        }
    }

    fn borrow2<'a>(&'a self) -> &'a int {
        match (self) {
            // WORKS
            &Foo(ref v) => &**v
        }
    }

    fn borrow3<'a>(&'a self) -> &'a int {
        match (self) {
            // WORKS
            &Foo(ref v) => do_borrow(*v)
        }
    }
}



struct FooVec(~[int]);

impl FooVec {
    fn borrow1<'a>(&'a self) -> &'a [int] {
        match (self) {
            // error: mismatched types: expected `&'a [int]` but found
            // `~[int]` ([] storage differs: expected &'a  but found ~)
            &FooVec(ref v) => *v
        }
    }

    fn borrow2<'a>(&'a self) -> &'a [int] {
        match (self) {
            // error: type ~[int] cannot be dereferenced
            &FooVec(ref v) => &**v
        }
    }

    fn borrow3<'a>(&'a self) -> &'a [int] {
        match (self) {
            // error: mismatched types: expected `&'a [int]` but found
            // `&<V2>` (expected vector but found &-ptr)
            &FooVec(ref v) => do_borrow(*v)
        }
    }
}
--------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140118/88bed08b/attachment-0001.html>


More information about the Rust-dev mailing list