Skip to content

.clone() on Vec<T> returns &[T] when T does not implement Clone #19017

Closed
@JustAPerson

Description

@JustAPerson
fn main() {
    struct Test;
    let v = vec![Test];
    let w: Vec<Test> = v.clone();
}
<anon>:4:24: 4:33 error: mismatched types: expected `collections::vec::Vec<main::Test>`, found `&[main::Test]` (expected struct collections::vec::Vec, found &-ptr)
<anon>:4     let w: Vec<test> = v.clone();

The solution to this error is to derive the Clone trait for Test.

Since Vec<Test> does not implement Clone trait, Vec<Test> is automatically coerced to &[Test], which does implement Clone, by way of the Deref trait.

This behavior and error are unintuitive. Perhaps better information could be reported here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions