rust - Why do I need to use an extra `::` prefix to access an imported struct? -
in lib.rs
wanted use std::fs::file
.
here example code:
use std::fs::file; use std::io::read; impl css { pub fn save_result_to_file(file_to_save: string) { println!("saving output {}", file_to_save); let mut f = file::open(file_to_save).expect("unable open file"); // let mut f = ::file::open(file_to_save).expect("unable open file"); -> works } }
without presence of ::
before file
i'm getting compiler error:
| let mut f = file::open(file_to_save).expect("unable open file"); | ^^^^^^^^^^ use of undeclared type or module `file`
my question - ::
prefix necessary? i'm sure it's not, cannot see how this.
you can think of ::
module path separator same way /
in file path, , leading /
means root directory, leading ::
refers application's root module.
when import item use
name of item becomes (private default) member of module, , can referred other modules using absolute or relative paths. fact having problem tells me use
statements in root module, while other code in child module. why commenters above unable reproduce code posted.
you have module structure this:
use std::fs::file; use std::io::read; mod foo { struct css {} impl css { pub fn save_result_to_file(file_to_save: string) { println!("saving output {}", file_to_save); let mut f = ::file::open(file_to_save).expect("unable open file"); } } }
the leading ::
necessary because file
imported root module, using in child module. if move import actual module contains code work fine without leading ::
:
mod foo { use std::fs::file; use std::io::read; struct css {} impl css { pub fn save_result_to_file(file_to_save: string) { println!("saving output {}", file_to_save); let mut f = file::open(file_to_save).expect("unable open file"); } } }
Comments
Post a Comment