I recently read the following line of code:
use fmt::{self, Debug};
What does the self
keyword in the above statement mean?
I recently read the following line of code:
use fmt::{self, Debug};
What does the self
keyword in the above statement mean?
Using self
in that context allows you to bind a module plus some of it's child elements into the current scope with a single use
statement.
Without self:
use a::b::{c,d};
// Now you can refer to a::b::c as c and a::b::d as d
// but if you need to refer to a::b as a::b
With self:
use a::b::{self, c, d};
// Now b refers to a::b as well
fmt
contains the struct Result
. Personally I don't want to overwrite Result
in my namespace, so I use fmt::Result
. I.e. fn fmt(&self, f: Formatter) -> fmt::Result;
. You only need this, if you want to use the module itself. –
Confront fmt
, if you remove self
–
Confront boo
just before. Why accepting an answer if you don't understand it? –
Confront use
allows only absolute paths, 'fmt' should be start of the path, module, right.? so it should be at least declared with mod fmt
erlier - if so, use fmt::{self} is redeclaration. –
Neurotic fmt
reimported here).? –
Neurotic self
here refers to the module itself, i.e. your line is equivalent to the two lines
use fmt::Debug;
use fmt;
Using self
in that context allows you to bind a module plus some of it's child elements into the current scope with a single use
statement.
Without self:
use a::b::{c,d};
// Now you can refer to a::b::c as c and a::b::d as d
// but if you need to refer to a::b as a::b
With self:
use a::b::{self, c, d};
// Now b refers to a::b as well
fmt
contains the struct Result
. Personally I don't want to overwrite Result
in my namespace, so I use fmt::Result
. I.e. fn fmt(&self, f: Formatter) -> fmt::Result;
. You only need this, if you want to use the module itself. –
Confront fmt
, if you remove self
–
Confront boo
just before. Why accepting an answer if you don't understand it? –
Confront use
allows only absolute paths, 'fmt' should be start of the path, module, right.? so it should be at least declared with mod fmt
erlier - if so, use fmt::{self} is redeclaration. –
Neurotic fmt
reimported here).? –
Neurotic © 2022 - 2024 — McMap. All rights reserved.