lotsoftools

Rust Base64

This snippet page provides an example of using Base64 encoding and decoding within the Rust programming language.

use std::str;
use base64::{encode, decode};

fn main() {
    let text = 'Hello, world!';
    let encoded = encode(text);
    let decoded = decode(&encoded).unwrap();
    let decoded_str = str::from_utf8(&decoded).unwrap();
    println!("{}", decoded_str);
}

First, we import the necessary modules for base64 encoding and decoding and for string handling.

In the main function, we define a string 'text'. The Base64 encode function is then used on this string which returns a base64 encoded version of the text.

Following this, we decode the base64 encoded string using the Base64 decode function. We also handle any errors during decoding with unwrap.

Finally, we convert the decoded byte array back into a string using 'str::from_utf8' and unwrap the result. In the end, we print the decoded string.