< 返回版块

colatea 发表于 2023-09-08 11:27

Tags:lazy_static

如题,大佬有什么方案在执行的过程中动态获取不同的全局变量不


use lazy_static::lazy_static;
use tokio::sync::Mutex;

lazy_static!{
    static ref S1: Mutex<String> = Mutex::new(String::new());
    static ref S2: Mutex<String> = Mutex::new(String::from("string2"));
}

pub struct Three;

impl Three {
    
    pub async fn show_static_string(index: &str) -> bool {
        
        let SS  = match index {
            "s1" => S1,
            "s2" => S2,
            _ => false
        };
        
        let s = SS.lock().await;
        println!("{}: {}", index, s);
        true
    }
}

我这些写报错,类型不对,没有思路

error[E0308]: `match` arms have incompatible types
  --> src\three.rs:24:21
   |
22 |           let SS  = match index {
   |  ___________________-
23 | |             "s1" => S1,
   | |                     -- this is found to be of type `S1`
24 | |             "s2" => S2,
   | |                     ^^ expected `S1`, found `S2`       
25 | |             _ => false
26 | |         };
   | |_________- `match` arms have incompatible types

不用了,搞定了

pub async fn show_static_string(index: &str) -> bool {
        
        let ref SS: Mutex<String>;
        
        SS = match index {
            "s1" => &S1,
            "s2" => &S2,
            _ => return false
        };
        
        let s = SS.lock().await;
        println!("{}: {}", index, s);
        true
    }

评论区

写评论
作者 colatea 2023-09-08 15:22

这个方法更好。感谢

--
👇
bestgopher:

pub async fn show_static_string(index: &str) -> bool {
        
        let s  = match index {
            "s1" => S1.lock().await,
            "s2" => S2.lock().await,
            _ => return false,
        };
        
        println!("{}: {}", index, s);
        true
    }
bestgopher 2023-09-08 11:51
pub async fn show_static_string(index: &str) -> bool {
        
        let s  = match index {
            "s1" => S1.lock().await,
            "s2" => S2.lock().await,
            _ => return false,
        };
        
        println!("{}: {}", index, s);
        true
    }
1 共 2 条评论, 1 页