To convert a ethereum_types::H256 to String in Rus

2020-04-14 11:50发布

问题:

when I tried to convert ethereum_types::H256 to String by using to_string()

use ethereum_types::H256;

fn main() {   
    let s = H256::zero();
    println!("{}", s);
}

I expect output to be

"0x0000000000000000000000000000000000000000000000000000000000000000" 

but output is

"0x0000…0000"

回答1:

This (weird) behaviour comes from the fixed-hash crate.

It implements several formatting traits:

  • Display which always elides the middle of the hash.
  • Debug which is equivalent to LowerHex alternate mode.
  • LowerHex and UpperHex which never elide .

Therefore, to get the output you want, use LowerHex with alternate mode:

    println!("{:#x}", s);

(alternatively you can use Debug, but the output of Debug should generally not be relied upon)