Sha256 result to string

I have the following code:

        let mut sha256 = Sha256::new();
        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[E0308]: mismatched types
  --> src/
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();
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


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:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.