What is the purpose of `b` here?

Viewed 443

In this code :

#![allow(unused)]
fn main() {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;

let mut hasher = DefaultHasher::new();

hasher.write_u32(1989);
hasher.write_u8(11);
hasher.write_u8(9);
hasher.write(b"Huh?");

println!("Hash is {:x}!", hasher.finish());
}

I understand write_u8, u32, i32 but what's the point of b and why not some other letter, newbie programmer, any suggestion would be appreciated!

1 Answers

Any string prefixed by a b tells the compiler that the string should be treated as a byte sequence. This is called a byte string literal.

You can read more about it in the The Rust Reference. In short, a string in Rust is a valid sequence of unicode characters and hence it can be represented as &[u8] (A slice containing unsigned 8-bit integers). A byte is also a 8 bit-integer so it is considered as a sequence of unicode bytes.

The hasher.write(...) function takes a &[u8], basically a sequence of bytes as parameter. In order to convert your &str to bytes, you prefix it with a b

Related