Why does std::vec::Vec::to_vec() exist?

std::vec::Vec also implements the Clone trait, so a Vec can be copied with ::clone(). Why does it also provide ::to_vec()?

Generally, I would expect common trait methods for common functionality to be preferred over harder-to-remember per-type method names.

If this were some pre-Clone legacy method, I'd expect it to be marked deprecated. But it does not appear to be marked so.

Thanks.

Edit: Context: rustc 1.43.1 prompted me to copy a &Vec<u8> to Vec<u8> with to_vec(), when it seems like clone() is (arguably) better:

    |        ^^^^
    |        |
    |        expected struct `std::vec::Vec`, found reference
    |        help: try using a conversion method: `data.to_vec()`

to_vec is not a method of the Vec type, but a method of the [T] or “slice” type. It can be called on any type that derefs to a slice, including Vec.

4 Likes

Thanks. I was confused because all of the slice methods show up on Vec in std::vec - Rust . It seems this is because Vec implements Deref<Target = [T]>?

Edit: And the documentation is not super clear (to me!) on an individual method basis what the current impl is.

Yes, that's correct.

1 Like

Thanks! Is this something we could document better, or already something that has been considered and dismissed?

It could probably be improved. One problem is when a doc page gets so long that the section header is off-screen after scrolling to a specific method, making it impossible to see the full context. Keeping this information visible would be really useful.

2 Likes

Yeah, that would be a nice way to solve the problem. I tend to be an old HTML4 curmudgeon and would just throw the impl inline with every single method, but a top bar that follows down the page would also be easy to understand for me.

Thanks again. I'm about 8 days into Rust and still getting familiar with the basics like this.

CSS has position: sticky, which could certainly be used. It's supported in all modern browsers.

4 Likes

Just to follow up on my previous comment, adding the following CSS to any page on docs.rs does the trick

.small-section-header {
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: #353535;
}

Naturally, the background-color will need to change alongside the theme. The expand/collapse button is still visible underneath this, as the element doesn't sit far enough to the left. But as a quick fix, this little snippet of code suffices (and in my opinion is actually far better).

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.