Sha256 result to string

I have the following code:

        let mut sha256 = Sha256::new();
        sha256.update(ip_address);
        let ip_address_hash : String = sha256.finalize();

I'm using this Sha2 crate.
I can't seem to figure out how to convert this result to a String.

Error

error[E0308]: mismatched types
  --> src/main.rs:37:40
   |
37 |         let ip_address_hash : String = sha256.finalize();
   |                               ------   ^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found struct `sha2::digest::generic_array::GenericArray`
   |                               |
   |                               expected due to this
   |
   = note: expected struct `std::string::String`
              found struct `sha2::digest::generic_array::GenericArray<u8, sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UInt<sha2::digest::generic_array::typenum::UTerm, sha2::digest::consts::B1>, sha2::digest::consts::B0>, sha2::digest::consts::B0>, sha2::digest::consts::B0>, sha2::digest::consts::B0>, sha2::digest::consts::B0>>`

finalize() returns some kind of generic_array, but the documentation of the crate is not clear at all about this...

The following works:

let mut sha256 = Sha256::new();
sha256.update(ip_address);
let ip_address_hash: String = format!("{:X}", sha256.finalize());

Usage found here.
GenericArray's docs are here and it implements std::fmt::UpperHex and std::fmt::LowerHex

3 Likes

Thanks! But why does this work:

let ip_address_hash : String = format!("{:X}", sha256.finalize());

But this don't:

let ip_address_hash : String = format!("{}", sha256.finalize());

They're both strings, no? And what exactly what :X again?

{:x} means format as hexadecimal using the std::fmt::UpperHex trait, which is implemented for GenericArray. {} means format normally using the std::fmt::Display trait, which is not implemented for GenericArray.

1 Like

Perfectly clear :ok_hand:t2: