我有一个在main
(第 9 行)中初始化的变量,我想在我的一个路由处理程序中访问对这个变量的引用。
#[get("/")]
fn index() -> String {
return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?
}
fn main() {
let redis_conn = fetch_data::get_redis_connection(); // initialized here
rocket::ignite().mount("/", routes![index]).launch();
}
Run Code Online (Sandbox Code Playgroud)
在其他语言中,这个问题可以通过使用全局变量来解决。
我有以下代码:
private extractInitials(fullname: string): string {
const initials = fullname
.replace(/[^a-zA-Z- ]/g, '')
.match(/\b\w/g)
.join('')
.toUpperCase();
return initials.substring(0, 2);
}
Run Code Online (Sandbox Code Playgroud)
[ts] Object is possibly 'null'. [2531]
所以我试过了
if fullname { const initials .... return ... } else return '';
原来打字稿正在抱怨这个家伙
fullname.replace(/[^a-zA-Z- ]/g, '')
这是有道理的,因为这可能最终成为一个空字符串
所以我做了
const t = fullname.replace(/[^a-zA-Z- ]/g, '')
if(t) { /* do the rest */ } else return ''
Run Code Online (Sandbox Code Playgroud)
它仍然给了我对象可能是null错误.我知道不是.我该如何解决?