How to use base64 crate in Rust encoding

Encode and decode strings in Rust using the base64 crate with the standard engine and Engine trait.

Use the base64 crate by adding it to your Cargo.toml and importing the Engine trait to encode or decode strings.

use base64::{Engine as _, engine::general_purpose};

fn main() {
    let text = "Hello, world!";
    let encoded = general_purpose::STANDARD.encode(text);
    let decoded = general_purpose::STANDARD.decode(encoded).unwrap();
    println!("Original: {}", text);
    println!("Encoded: {}", encoded);
    println!("Decoded: {}", String::from_utf8(decoded).unwrap());
}

Add this to your Cargo.toml:

[dependencies]
base64 = "0.22"