rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.49k stars 1.55k forks source link

string_lit_as_bytes doesn't work correctly #1402

Open farodin91 opened 7 years ago

farodin91 commented 7 years ago

I'm not shure why this not work correct. "key".as_bytes().to_owned() => b"key".to_owned() for type Vec<u8>

clarfonthey commented 7 years ago

It's because b"key" is interpreted as [u8; 3] when to_owned is expecting [u8]. This is something that should be fixed on the compiler end, but for now, it's an error in the lint.

sinkuu commented 7 years ago

This doesn't seem to be a compiler issue. to_owned clones things that can be cloned (impl<T> ToOwned for T where T: Clone { type Owned = T; }), and b"key" is a [u8; 3] which is Clone.

Try using [T]::to_vec; b"key".to_vec() returns Vec<u8>.

farodin91 commented 7 years ago

@sinkuu .to_vec() works perfect for me. Thank you.

dtolnay commented 4 years ago

Just sharing a concrete repro for "doesn't work":

fn f(_: Vec<u8>) {}

fn main() {
    f("...".as_bytes().to_owned());
}

Suggestion by clippy:

warning: calling `as_bytes()` on a string literal
  --> src/main.rs:4:7
  |
4 |     f("...".as_bytes().to_owned());
  |       ^^^^^^^^^^^^^^^^ help: consider using a byte string literal instead: `b"..."`
  |
  = note: `#[warn(clippy::string_lit_as_bytes)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#string_lit_as_bytes

So we change:

-     f("...".as_bytes().to_owned());
+     f(b"...".to_owned());

Resulting type error:

error[E0308]: mismatched types
  --> src/main.rs:4:7
  |
4 |     f(b"...".to_owned());
  |       ^^^^^^^^^^^^^^^^^
  |       |
  |       expected struct `Vec`, found array `[u8; 3]`
  |       help: try using a conversion method: `b"...".to_owned().to_vec()`
  |
  = note: expected struct `Vec<u8>`
              found array `[u8; 3]`