Skip to content

Allow borrowing a whole vec of pointers #3849

@jruderman

Description

@jruderman

Most library functions can take & pointers, which is awesome. But library functions that take a vec of pointers have to decide how those pointers will be allocated, limiting their flexibility.

The motivating example is str::concat. It is a pure function that takes &[~str] and creates a new string with the concatenation of the input strings. It seems to me that it would be safe for it to take &[&str] instead. (The slice is constant, and the callee is pure, so the pointers should remain valid.) But currently, that prevents a vec of ~strs from being passed.

(For the special case of strings, there's the slight complication that sys::size_of::<&static/str>() is larger than sys::size_of::<~str>()...)

use str;

/// Concatenate a vector of strings
pure fn my_concat(v: &[&str]) -> ~str {
    let mut s: ~str = ~"";
    for vec::each(v) |ss| {
        unsafe { str::push_str(&mut s, *ss) };
    }
    move s
}

pure fn my_sum(v: &[&int]) -> int {
    let mut sum = 0;
    for vec::each(v) |summand| {
        sum += **summand;
    }
    sum
}

fn main()
{
    // These are allowed
    assert my_concat(["1", "A"]) == ~"1A";
    assert my_sum([&42, &13]) == 55;

    // These are not allowed. Why not?
    assert my_concat([~"1", ~"A"]) == ~"1A";
    assert my_concat([@"1", @"A"]) == ~"1A";
    assert my_sum([~42, ~13]) == 55;
    assert my_sum([@42, @13]) == 55;
}

gives me errors like

29:22: 29:33 error: mismatched types: expected `&/[&int]` but found `[~<VI4>]/2` (expected &-ptr but found ~-ptr)
29         assert my_sum([~42, ~13]) == 55;
                         ^~~~~~~~~~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsE-hardCall for participation: Hard difficulty. Experience needed to fix: A lot.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions