在Rust中将字符串转换为H256。

huangapple go评论69阅读模式
英文:

To convert a String to H256 in Rust

问题

如何将类似于"0x0000000000000000000000000000000000000000000000000000000000000000"的字符串转换为H256类型?我认为应该有一种简单的方法,就像一行代码那样。

我找到了一些库,但是没有找到简单的解决办法。

英文:

when I get a string like "0x0000000000000000000000000000000000000000000000000000000000000000", how to convert it to H256 type? I thought there is a simple way like a oneline code.

I found some crate, but can`t find a simply way to solve that.

答案1

得分: 1

Just use String.parse() method.
String.parse() can parse into any type that implements the FromStr trait, like Struct ethers::core::types::H256.

use ethers::core::types::H256;

fn main() {
    let a: H256 = "0x0000000000000000000000000000000000000000000000000000000000000000".parse().unwrap();
    //using turbofish syntax.
    let b = "0x1234567890987654321234566535655565653565666656536566565656656560".parse::<H256>().unwrap();

    println!("{}\n{}", a, b);
}
//0x0000…0000
//0x1234…6560
英文:

Just use String.parse() method.
String.parse() can parse into any type that implements the FromStr trait, like Struct ethers::core::types::H256.

use ethers::core::types::H256;

fn main() {
    let a: H256 = &quot;0x0000000000000000000000000000000000000000000000000000000000000000&quot;.parse().unwrap();
    //using turbofish syntax.
    let b = &quot;0x1234567890987654321234566535655565653565666656536566565656656560&quot;.parse::&lt;H256&gt;().unwrap();

    println!(&quot;{}\n{}&quot;, a, b);
}
//0x0000…0000
//0x1234…6560

答案2

得分: 0

Rust:

use ckb_types::h256;
h256!("0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49")

cargo.toml:

ckb-types = "0.108"
英文:

use Macro ckb_types::h256

Rust :

use ckb_types::h256;
h256!(&quot;0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49&quot;)

cargo.toml:

ckb-types = &quot;0.108&quot;

huangapple
  • 本文由 发表于 2023年5月17日 11:13:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定