我正在编写一个程序,该程序在终端中打印出您的SOL余额,但在获取时显示加载指示符。我使用solana_client机箱中的RpcClient来获取我的SOL平衡,但在一个新线程上,这样我就可以在请求运行时在主线程上旋转加载指示符。
我的问题是,如果我试图在传递给thread::spawn()
:的函数中使用RpcClient的指针,就会出现错误
fn main() {
let url = "https://api.testnet.solana.com".to_string();
let client = RpcClient::new(url);
let pubkey = Pubkey::from_str(ADDRESS).unwrap();
get_balance(&client, &pubkey);
}
fn get_balance(client: &RpcClient, pubkey: &Pubkey) {
let (tx, rx): (Sender<u64>, Receiver<u64>) = mpsc::channel();
let pubkey = pubkey.clone();
thread::spawn(move || {
let balance = client.get_balance(&pubkey).unwrap();
tx.send(balance)
.expect("failed to send back result throught tx channel");
});
let balance = spin(rx);
println!("balance: {}", balance);
}
错误:
error[E0759]: `client` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/main.rs:24:19
|
21 | fn get_balance(client: &RpcClient, pubkey: &Pubkey) {
| ---------- this data with an anonymous lifetime `'_`...
...
24 | thread::spawn(move || {
| ___________________^
25 | | let balance = client.get_balance(&pubkey).unwrap();
26 | | tx.send(balance)
27 | | .expect("failed to send back result throught tx channel");
28 | | });
| |_____^ ...is used here...
|
我试图使client
变量为静态,但这导致了另一个错误:
...
let client: &'static RpcClient = &RpcClient::new(url);
...
fn get_balance(client: &'static RpcClient, pubkey: &Pubkey) {
...
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:15:39
|
15 | let client: &'static RpcClient = &RpcClient::new(url);
| ------------------ ^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
| |
| type annotation requires that borrow lasts for `'static`
...
19 | }
| - temporary value is freed at the end of this statement
如果我试图在get_balance
函数中克隆client
,就像我对pubkey
所做的那样,我也会遇到同样的错误。
我可以通过传递url并在线程中创建一个新的RpcClient
来解决这个问题,但我正在努力理解为什么我当前的实现不起作用,以及在使用线程时应该如何处理这类问题。
由于Caesar的评论,我能够通过将客户端封装在Arc
:中来解决问题
fn main() {
let url = "https://api.testnet.solana.com".to_string();
let client = Arc::new(RpcClient::new(url));
let pubkey = Pubkey::from_str(ADDRESS).unwrap();
get_balance(&client, &pubkey);
}
fn get_balance(client: &Arc<RpcClient>, pubkey: &Pubkey) {
let (tx, rx): (Sender<u64>, Receiver<u64>) = mpsc::channel();
let client = client.clone();
let pubkey = pubkey.clone();
thread::spawn(move || {
let balance = client.get_balance(&pubkey).unwrap();
tx.send(balance)
.expect("failed to send back result throught tx channel");
});
let balance = spin(rx);
println!("balance: {}", balance);
}
我还找到了一个相关的帖子,其中的答案帮助我理解了为什么我的原始代码不起作用。