gpt4 book ai didi

rust - 返回对可选结构成员的可变引用

转载 作者:行者123 更新时间:2023-11-29 08:06:16 24 4
gpt4 key购买 nike

我想延迟连接到 Redis 数据库。我有一个 Db 结构,它包含 Redis Client。默认情况下,它是 None。这是 Python 中的示例代码:

import redis


class Db:

def __init__(self):
self.client = None

def get_client(self):
if self.client is None:
self.client = redis.StrictRedis(host='127.0.0.1')
return self.client

我试过了

extern crate redis;

use redis::Client;

struct Db {
client: Option<Client>,
}

impl Db {
fn new() -> Db {
Db { client: None }
}

fn get_client(&mut self) -> Result<&Client, &'static str> {
if let Some(ref client) = self.client {
Ok(client)
} else {
let connection_string = "redis://127.0.0.1";
match Client::open(connection_string) {
Ok(client) => {
self.client = Some(client);
Ok(&self.client.unwrap())
}
Err(err) => Err("Error!"),
}
}
}
}

fn main() {
let mut db = Db::new();
db.get_client();
}

而且我有编译错误。我几乎明白编译器说的是什么,但我不知道如何解决这个问题。

    error: borrowed value does not live long enough
--> src/main.rs:28:29
|
28 | Ok(&self.client.unwrap())
| ^^^^^^^^^^^^^^^^^^^^ does not live long enough
29 | },
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 19:66...
--> src/main.rs:19:67
|
19 | fn get_client(&mut self) -> Result<&Client, &'static str> {
| ^

error[E0507]: cannot move out of borrowed content
--> src/main.rs:28:29
|
28 | Ok(&self.client.unwrap())
| ^^^^ cannot move out of borrowed content

最佳答案

如果您调用 unwrap() 你动T来自 Option .因为你只借了self这导致了 cannot move out of borrowed content错误。

如果你想借一个Option<T>里面的值你可以使用 as_ref 方法:

extern crate redis;

use redis::Client;

struct Db {
client: Option<Client>,
}

impl Db {
fn new() -> Db {
Db { client: None }
}

fn get_client(&mut self) -> Result<&Client, &'static str> {
if let Some(ref client) = self.client {
Ok(client)
} else {
let connection_string = "redis://127.0.0.1";
match Client::open(connection_string) {
Ok(client) => {
self.client = Some(client);
Ok(self.client.as_ref().unwrap())
}
Err(_) => Err("Error!"),
}
}
}
}

fn main() {
let mut db = Db::new();
db.get_client().expect("get_client failed");
}

关于rust - 返回对可选结构成员的可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com