# Vec\<u8\> -\> String

**URL:** <https://users.rust-lang.org/t/vec-u8-string/91528>\
**Category:** help\
**Created:** [March 27, 2023, 12:07am UTC](https://users.rust-lang.org/t/vec-u8-string/91528 "2023-03-27T00:07:12Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![billhaber](https://avatars.discourse-cdn.com/v4/letter/b/f19dbf/32.png) [@billhaber](https://users.rust-lang.org/u/billhaber)\
**Post date:** [March 27, 2023, 12:07am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/1 "2023-03-27T00:07:12Z")

</div>

I'm new to Rust and have been trying out the code.

I have a Vec that I want to convert to a String

The few solutions I have found do not compile. It seems conversion should be simple. What am I misunderstanding?.

---

<div class="post-metadata">

**Author:** ![semicoleon](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/semicoleon/32/22313_2.png) [@semicoleon](https://users.rust-lang.org/u/semicoleon)\
**Post date:** [March 27, 2023, 12:34am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/2 "2023-03-27T00:34:14Z")

</div>

You can use [`String::from_utf8`](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8) to create a String from a `Vec<u8>` in a way that avoids creating allocations. It will return an error if your bytes contain invalid utf8 sequences.

[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a586c43879eb36fa5711ffdded604560)

```rust
fn main() {
    let bytes: Vec<_> = b"here's a byte string".to_vec();

    let string = String::from_utf8(bytes).expect("Our bytes should be valid utf8");

    println!("{string}")
}

```

---

<div class="post-metadata">

**Author:** ![billhaber](https://avatars.discourse-cdn.com/v4/letter/b/f19dbf/32.png) [@billhaber](https://users.rust-lang.org/u/billhaber)\
**Post date:** [March 27, 2023, 1:58am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/3 "2023-03-27T01:58:56Z")

</div>

I notice the vec type is not u8 but taken from your initializing byte string. My problem is u8 which panics when you are using from\_utf8

---

<div class="post-metadata">

**Author:** ![Michael-F-Bryan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/michael-f-bryan/32/28749_2.png) [@Michael-F-Bryan](https://users.rust-lang.org/u/Michael-F-Bryan)\
**Post date:** [March 27, 2023, 2:13am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/4 "2023-03-27T02:13:20Z")

</div>

> [@billhaber](#):
>
> My problem is u8 which panics when you are using from\_utf8

This code snippet initializes a `Vec<u8>` and converts it to a `String` using `String::from_utf8`. Remember that this method returns a `Result<String, FromUtf8Error>`, so if the bytes are not valid UTF-8, it will return an error. If you expect that your data might contain invalid UTF-8 sequences, you should handle the error appropriately instead of using `expect()`. For example, you can use pattern matching:

```rust
fn main() {
    let bytes: Vec<_> = b"here's a byte string".to_vec();

    match String::from_utf8(bytes) {
        Ok(string) => println!("{}", string),
        Err(e) => println!("Error: {}", e),
    }
}

```

This code will print the error message if the conversion fails, instead of panicking.

That still doesn't fix your problem though. I'd look at the raw data and see whether it is actually a string (e.g. by saving to a file and opening it in an editor or using a hexdump tool like `xxd`). The data you are trying to read might actually be binary and not text.

Alternatively, there is `String::from_utf8_lossy()` which will replace invalid UTF-8 characters with the UTF-8 replacement character (�). This can help if something happened to make just a small part of the text corrupted (unlikely given how reliable disks are today and TCP's guarantees).

If you are sure the `Vec<u8>` contains text, it might be in an encoding other than UTF-8. Rust strings only work with UTF-8 text, so you'll need to reach for something like [the `encoding` crate](https://docs.rs/encoding/latest/encoding/) to handle other text encodings.

---

<div class="post-metadata">

**Author:** ![billhaber](https://avatars.discourse-cdn.com/v4/letter/b/f19dbf/32.png) [@billhaber](https://users.rust-lang.org/u/billhaber)\
**Post date:** [March 27, 2023, 2:29am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/5 "2023-03-27T02:29:59Z")

</div>

Thanks for clearing up my misunderstanding, Obviously I need to refine my code based on your comments.

---

<div class="post-metadata">

**Author:** ![MMK](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mmk/32/33449_2.png) [@MMK](https://users.rust-lang.org/u/MMK)\
**Post date:** [March 27, 2023, 12:03pm UTC](https://users.rust-lang.org/t/vec-u8-string/91528/6 "2023-03-27T12:03:40Z")

</div>

or you can use `std::str::from_utf_8`,  
the advantage is that it returns &str,does not clone data.  
play\_ground:[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=79783ed30d41bbf157a801a3327b6305)

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [March 27, 2023, 1:14pm UTC](https://users.rust-lang.org/t/vec-u8-string/91528/7 "2023-03-27T13:14:57Z")

</div>

`String::from_utf8()` doesn't clone the data, either.

---

<div class="post-metadata">

**Author:** ![MMK](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mmk/32/33449_2.png) [@MMK](https://users.rust-lang.org/u/MMK)\
**Post date:** [March 28, 2023, 8:57am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/8 "2023-03-28T08:57:04Z")

</div>

thanks for the clarification , I didn't know

---

<div class="post-metadata">

**Author:** ![MMK](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mmk/32/33449_2.png) [@MMK](https://users.rust-lang.org/u/MMK)\
**Post date:** [March 28, 2023, 9:04am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/9 "2023-03-28T09:04:04Z")

</div>

It would be correct to say that `std::str::from_utf_8` just borrows data,not how `String::from_utf8()`

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [March 28, 2023, 9:31am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/10 "2023-03-28T09:31:42Z")

</div>

Yes, they do different things w.r.t. ownership, but neither of them clones. `str::from_utf8()` avoids cloning by borrowing, while `String::from_utf8()` avoids cloning by moving.

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [March 28, 2023, 9:39am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/11 "2023-03-28T09:39:44Z")

</div>

`std::str::from_utf8` both takes `(&[u8])` and returns (`Result<&str, _>`) borrowed data. If you have a `v: Vec<u8>` pass it `&v`, that will coerce to a `&[u8]` and be a borrow of your `Vec<u8>`. If you only have a borrow or if you don't want to lose ownership of a `Vec` you have, use this one. If you need a `String` and not a (borrowed) `&str`, subsequently use `.to_string()` on the `&str`. \[1\]

`String::from_utf8` both takes (`Vec<u8>`) and returns (`Result<String, _>`) owned data. If you have a `Vec<u8>` and don't mind losing ownership of it, use this one. \[2\]

* * *

1. It will only do the UTF8 check once and this way you won't clone unless you have valid UTF8. 

2. It will only do the UTF8 check once and this way you won't clone at all.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [June 26, 2023, 9:39am UTC](https://users.rust-lang.org/t/vec-u8-string/91528/12 "2023-06-26T09:39:46Z")

</div>

Closed on June 26, 2023, 9:39am UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
