Access to nested structures without moving

I have these structures:

#[derive(Debug, RustcDecodable)]
struct Config {
    ssl: Option<SslConfig>,
}

#[derive(Debug, RustcDecodable)]
struct SslConfig {
    key: Option<String>,
    cert: Option<String>,
}

They are populated from the file toml. It works great. Since I got Option<T>it, I need to either call unwrap()or do it match.

But if I want to do the following:

let cfg: Config = read_config(); // Reads a File, parses it and returns the Config-Struct
let keypath = cfg.ssl.unwrap().key.unwrap();
let certpath = cfg.ssl.unwrap().cert.unwrap();

This will not work because it cfg.sslmoves to keypath. But why is this moving? I call unwrap()on sslto get the key (and unwrap()it). So, key.unwrap()should the result be moved?

? ( )? #[derive(Debug, RustcDecodable, Copy, Clone)], , Copy String. Copy Vec<u8> . ?

+4
2

Option::unwrap? :

fn unwrap(self) -> T

(cfg.ssl ).

, , Option<T> &T, &self ( , )... clone Option unwrap.

... as_ref:

fn as_ref(&self) -> Option<&T>

:

let keypath /*: &String*/ = cfg.ssl.as_ref().unwrap().key.as_ref().unwrap();
                                    ^~~~~~~               ^~~~~~~~
+5

, key.unwrap() ?

, . , unwrap(). :

fn unwrap(self) -> T { ... }

self, . ssl.unwrap() !

:

cfg.ssl.unwrap().key.unwrap();

cfg.ssl unwrap(), unwrap(). , , cfg.ssl . , unwrap(), :

let ssl = cfg.ssl.unwrap();
let keypath = ssl.key.unwrap();
let certpath = ssl.cert.unwrap();

as_ref() , (, , ).

+3

Source: https://habr.com/ru/post/1657077/


All Articles