I have an LdapConn that I am passing around to multiple functions. Currently I'm passing the ldap variable to a function and then returning it. Inside of the function I'm not doing any dangerous modification of the ldapConn, I'm just changing the search result part. Passing it around works, but what's the best way to make a variable last the length of my program?
//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 is not cloneable
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.
You should always take the least intrusive thing you can. That means: If you can take a &, you should do that. If not, you should take a &mut if you can. And only if you have no other option should you take ownership of a value. In your case, you're going to need unique access to the connection, so & is out of the question. &mut, however, is fair game.
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);
What you've stumbled upon (namely, that you can pass ownership and take it back) is called linear typing. It's the origin of Rust's type system, on which the borrow checker is built. There's nothing inherently wrong (mathematically) with always passing ownership and taking it back, except that it gets very tedious to constantly be accepting ownership back of things you just gave away. That's exactly why Rust allows borrowing, to prevent that sort of situation from getting out of hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With