113

This seems trivial, but I cannot find a way to do it.

For example,

fn f(s: &[u8]) {}

pub fn main() {
    let x = "a";
    f(x)
}

Fails to compile with:

error: mismatched types:
 expected `&[u8]`,
    found `&str`
(expected slice,
    found str) [E0308]

documentation, however, states that:

The actual representation of strs have direct mappings to slices: &str is the same as &[u8].

nbro
  • 15,395
  • 32
  • 113
  • 196
ynimous
  • 4,642
  • 6
  • 27
  • 43
  • 3
    The fact that this is the one of about five google results for this error message seems crazy to me! I hit this in my first test program post-1.0 (implementing "cat"). – Derrick Turk Jul 26 '15 at 23:43

1 Answers1

128

You can use the as_bytes method:

fn f(s: &[u8]) {}

pub fn main() {
    let x = "a";
    f(x.as_bytes())
}

or, in your specific example, you could use a byte literal:

let x = b"a";
f(x)
fjh
  • 12,121
  • 4
  • 46
  • 46
  • 10
    I'd like to add that the documentation relates to the *representation*, but conceptually a string slice guarantees that its content is valid UTF-8, whereas a byte slice doesn't. – llogiq Jul 08 '15 at 10:52