It would be necessary (but not sufficient*) for them to have the same in-memory representation, and currently ~str and &str don't.

~str is `*{ length: uint, capacity: uint, data... }`, a pointer to a vector with the length and capacity stored inline, i.e. one word; &str is just `{ data: *u8, length: uint }`, a pointer to a chunk of memory along with the length of that chunk, i.e. two words.


(*E.g. std::cell::Cell<uint> and uint have the same in-memory representation, but coercing a &[uint] to a &[Cell<uint>] is a very bad idea... when it would theoretically be possible relates to subtyping/type variance.)

Huon

On 24/03/14 17:36, Phil Dawes wrote:
To complete my understanding: is there a reason a 'sufficiently smart compiler' in the future couldn't do this conversion implicitly?

I.e. if a function takes a borrowed reference to a container of pointers, could the compiler ignore what type of pointers they are (because they won't be going out of scope)?

Thanks,

Phil


On Sun, Mar 23, 2014 at 7:14 AM, Patrick Walton <[email protected] <mailto:[email protected]>> wrote:

    On 3/23/14 12:11 AM, Phil Dawes wrote:

        On Sun, Mar 23, 2014 at 2:04 AM, Patrick Walton
        <[email protected] <mailto:[email protected]>
        <mailto:[email protected] <mailto:[email protected]>>>
        wrote:

            Why not change the signature of `search_crate` to take `~str`?

            Patrick


        Hi Patrick,

        The main reason I haven't done this is that it is already used
        from a
        bunch of places where a path is &[&str] as the result of an
        earlier
        split_str("::")
        e.g.
                let path : ~[&str] = s.split_str("::").collect();
                ...
                search_crate(path);


    Ah, I see. Well, in that case you can make a trait (say,
    `String`), which implements a method `.as_str()` that returns an
    `&str`, and have that trait implemented by both `&str` and `~str`.
    (IIRC the standard library may have such a trait already, for `Path`?)

    You can then write:

        fn search_crate<T:String>(x: &[T]) {
            ...
            for string in x.iter() {
                ... string.as_str() ...
            }
        }

    And the function will be callable with both `&str` and `~str`.
    Again, I think the standard library has such a trait implemented
    already, for this use case.

    Patrick




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

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

Reply via email to