我正在尝试通过名为
new
的关联函数为结构创建一个“构造函数”。在这个“构造函数”中,我需要访问我已经定义/实例化的结构的字段之一(在“构造函数”内)。公钥需要从私钥派生,即结构中的第二个字段是从第一个字段派生的。这在 Rust 中可能吗?或者我应该尝试不同的模式?
一个想法是我可以将私钥作为参数传递给“构造函数”,但我认为这不能满足我针对此特定情况的目标。我认为在创建时结构本身应该生成随机熵
&mut OsRng
而不是由调用方法传入。
将
&mut self
传递给“构造函数”也不起作用,因为在实例化时,没有“自我”可传递到 Wallet::new()
函数中。
防爆代码。
pub struct Wallet {
private_key: SecretKey<Secp256k1>,
public_key: PublicKey<Secp256k1>,
}
impl Wallet {
pub fn new() -> Wallet {
Wallet {
private_key: SecretKey::random(&mut OsRng),
public_key: self.private_key.public_key(), // <- This is where the error occurs, there is no
// "self" object to access and just using
// "private_key.public_key()" leads to the error:
// "cannot find the value private_key in this scope"
}
}
}
实例化一个
Wallet
对象:
let wallet: Wallet = Wallet::new();
您不需要访问
self
:
pub struct Wallet {
private_key: SecretKey<Secp256k1>,
public_key: PublicKey<Secp256k1>,
}
impl Wallet {
pub fn new() -> Wallet {
let private_key = SecretKey::random(&mut OsRng);
Wallet {
private_key: private_key,
public_key: private_key.public_key()
}
}
}