我有一个要传递给多个函数的 LdapConn。 目前我将 ldap 变量传递给一个函数然后返回它。在函数内部,我没有对 ldapConn 进行任何危险的修改,我只是更改了搜索结果部分。传递它是可行的,但是让变量持续整个程序长度的最佳方法是什么?
//main.rs
let mut ldap: LdapConn = LdapConn::with_settings(
LdapConnSettings::new()
.set_no_tls_verify(true)
.set_starttls(true),
"ldaps://ldap.example.com:636",
)
.unwrap();
//other_file.rs
pub fn get_group_members(group: &str, mut conn: LdapConn) -> (LdapConn, Vec<String>) {
let (s_filter, ou) = split_dn(group);
let search_result = conn
.search(
&ou,
Scope::Subtree,
&format!("(&(objectClass=group)({}))", s_filter),
vec!["member"],
)
.unwrap();
let resp: Vec<
std::collections::HashMap<std::string::String, std::vec::Vec<std::string::String>>,
> = search_result
.0
.iter()
.map(|x| SearchEntry::construct(x.clone()).attrs)
.collect();
(conn, trim_users(resp[0].get("member").unwrap().to_vec()))
}
//main.rs
let (ldap, users) = get_group_members(group, ldap);
PS: LdapConn 不可克隆
https://docs.rs/ldap3/latest/ldap3/struct.LdapConn.html
The API is virtually identical to the asynchronous one. The chief difference is that LdapConn is not cloneable: if you need another handle, you must open a new connection.
最佳答案
您应该始终尽量减少干扰。这意味着:如果你能接受 &
,你就应该这样做。如果没有,如果可以的话,你应该使用 &mut
。并且只有在您别无选择的情况下,您才应该拥有一个值(value)。在您的情况下,您将需要对连接的唯一访问权限,因此 &
是不可能的。然而,&mut
是公平的游戏。
pub fn get_group_members(group: &str, conn: &mut LdapConn) -> Vec<String> {
...
}
// main.rs
let mut ldap = ...;
let users = get_group_members(group, &mut ldap);
您偶然发现的(即,您可以传递所有权并收回所有权)称为 linear typing .它是 Rust 类型系统的起源,借用检查器就是基于它构建的。始终传递所有权并收回所有权本身并没有什么错误(从数学上讲),只是不断接受您刚刚放弃的东西的所有权变得非常乏味。这正是 Rust 允许借用的原因,以防止这种情况失控。
关于rust - 我应该为变量添加生命周期还是在 Rust 函数之间传递它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73210168/