rust


How do I convert a Vector of bytes (u8) to a string


I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server. How do I convert the u8 vector to a String for printing?
To convert a slice of bytes to a string slice (assuming a UTF-8 encoding):
use std::str;
//
// pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
//
// Assuming buf: &[u8]
//
fn main() {
let buf = &[0x41u8, 0x41u8, 0x42u8];
let s = match str::from_utf8(buf) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
println!("result: {}", s);
}
The conversion is in-place, and does not require an allocation. You can create a String from the slice if necessary.
The library reference for the conversion function:
std::str::from_utf8
I prefer String::from_utf8_lossy:
fn main() {
let buf = &[0x41u8, 0x41u8, 0x42u8];
let s = String::from_utf8_lossy(buf);
println!("result: {}", s);
}
It turns invalid UTF-8 bytes into � and so no error handling is required. It's good for when you don't need that and I hardly need it. You actually get a String from this. It should make printing out what you're getting from the server a little easier.
Sometimes you may need to use the into_owned() method since it's clone on write.
If you actually have a vector of bytes (Vec<u8>) and want to convert to a String, the most efficient is to reuse the allocation with String::from_utf8:
fn main() {
let bytes = vec![0x41, 0x42, 0x43];
let s = String::from_utf8(bytes).expect("Found invalid UTF-8");
println!("{}", s);
}

Related Links

How do I hold a collection of one struct in another where lifetimes are not predictable?
Why does Rust have both call by value and call by reference?
Error: borrowed value is only… reference must be valid for
In Rust how do you pass a function as a parameter?
Obtaining rustdoc for particular function or trait
Rust slice ownership outlives its scope
What's purpose of ErrorKind::__Nonexhaustive?
A set type that preserves insertion order
Rust closure type mismatches of seemingly opposing natures
How can I build multiple binaries with Cargo?
borrowed value does not live long enough in this case ( Vec<&Fn(i32) -> i32> )
Mutability issue with self and collections in Rust
Recommended way to wrap C lib initialization/destruction routine
Return either a borrowed or owned type in Rust
Is there some way to not show a warning for non snake case identifiers?
Mismatched types: expected &str found String when assigning string

Categories

HOME
python-2.7
openshift
protocol-buffers
android-studio
xcode
eclipse-plugin
adfs3.0
scroll
hid
consul
docker-cloud
liferay-7
material-components
mailing-list
slide
cname
powermock
sonata
mahout-recommender
synthesis
phonegap-build
pickle
gitkraken
sqlplus
pst
web-config-transform
ruby-daemons
annotation-processing
macromedia
microsoft-certifications
xmlunit
gnu-classpath
subclassing
macports
cheat-engine
klee
distributed-caching
dagger
optionaldataexception
elasticsearch-aggregation
notesview
jshint
ipp-protocol
adblock
realstudio
dredd
qvtkwidget
mongodb-aggregation
gnome-terminal
connect-direct
kendo-editor
mpmovieplayercontroller
prefetch
d3v4
allegro
scheduledexecutorservice
thread-exceptions
deferred-rendering
urbit
jeditable
mousehover
calcite
wso2ml
gql
ocmockito
mgwt
dnsjava
vs-unit-testing-framework
utf8-decode
cout
accessory
meteor-collections
xmi
usb-flash-drive
ldif
bcdedit
dibs
oscilloscope
semicolon
examine
icenium
jsplitpane
audiotoolbox
workflow-manager-1.x
image-scanner
trialware
firebird1.5
liveconnect
snackjs
data-dump
aptitude
active-record-query
tessellation
asdoc
data-retrieval
downloadfile

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App