How do I print a vector of u8 as a string?

前端 未结 4 1162
误落风尘
误落风尘 2021-02-19 01:45

Here\'s my code:

let mut altbuf: Vec = Vec::new();

// Stuff here...

match stream.read_byte() {
    Ok(d) => altbuf.push(d),
    Err(e) => { pri         


        
4条回答
  •  梦毁少年i
    2021-02-19 02:11

    If you look at the String documentation, there are a few methods you could use. There's String::from_utf8 that takes a Vec, and there's also String::from_utf8_lossy which takes a &[u8].

    Note that a Vec is more-or-less an owned, resizable wrapper around a [T]. That is, if you have a Vec, you can turn it into a &[u8], most easily by re-borrowing it (i.e. &*some_vec). You can also call any methods defined on &[T] directly on a Vec (in general, this is true of things that implement the Deref trait).

提交回复
热议问题