Skip to content

Warn when using to_owned on already owned types #6715

@kangalio

Description

@kangalio

What it does

By virtue of deferencing to &[T], Vec implements several methods such as .to_owned() or .to_vec(). When called on Vec, these methods do the same thing as .clone(), all the while being more confusing ("why call to_owned or to_vec on something that already is a Vec and is owned?")

Categories

  • Kind: style

What is the advantage of the recommended code over the original code

As mentioned above, to_vec and to_owned are potentially misleading and confusing when used on Vec. clone is a clearer alternative.

Drawbacks

None.

Example

let a = vec![1, 2, 3];
let b = a.to_vec();

Could be written as:

let a = vec![1, 2, 3];
let b = a.clone();

Additional comments

Same applies to String with .to_owned() and .to_string(). Or PathBuf with .to_owned() and to_path_buf(). Or I suppose CString with .to_owned(). There's a lot of these cases in the standard library actually. Should those cases be handled using the same lint?

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsT-middleType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions