rustHow do you create a Rust string from a character array?
Creating a Rust string from a character array can be done using the String::from_utf8 function. This function takes a &[u8] as an argument and returns a Result<String, FromUtf8Error>.
Example code
let chars: &[u8] = &[104, 101, 108, 108, 111];
let string = String::from_utf8(chars).unwrap();
Output example
hello
The code above creates a &[u8] from the character array [104, 101, 108, 108, 111] and passes it to the String::from_utf8 function. The unwrap method is used to convert the Result<String, FromUtf8Error> into a String.
Code explanation
&[u8]: A type of array that contains 8-bit unsigned integers.String::from_utf8: A function that takes a&[u8]as an argument and returns aResult<String, FromUtf8Error>.unwrap: A method that converts aResult<String, FromUtf8Error>into aString.
Helpful links
More of Rust
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookbehind in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex captures in Rust?
- How to perform matrix operations in Rust?
- How to print a Rust HashMap?
- How to use non-capturing groups in Rust regex?
- How to match digits with regex in Rust?
- How to convert a Rust HashMap to a JSON string?
See more codes...