[solved] What to do when adding a trait cause a nameclash?


#1

Let say i have some code with an enum named Write.

enum Write {Something, Anything, Nothing}

fn main() {
    let mut file = std::fs::File::create("foo.txt").unwrap();
    ... // Lots of code
}

One day I decide I want to write something to the opened file. For that I need to add the Write trait.

use std::io::Write;

enum Write {Something, Anything, Nothing}

fn main() {
    let mut f = std::fs::File::create("foo.txt").unwrap();
    f.write_all(b"Hello, world!").unwrap();
    ... // Lots of code
}

This will generate the following error on compile:

error: import `Write` conflicts with type in this module

What is the best solution here? Are the programmer forced to rename the enum (and all usage of it in the code)? Or is there a way to use the Write trait without causing a name clash?

PS. I’m still new to rust. If this is explained somewhere in the docs (and I’ve just missed it) please let me know.


#2

Try something like this?

use std::io::Write as IoWrite;

#3

That works. Thank you.

Though I wonder if there are a way to solve this without getting a NameSubstitute in the local namespace which maybe never will be used. But maybe this is just me thinking about it all wrong.


#4

I think I got it. If I’ve understood this correctly, to solve this without using the use keyword:

use std::io::Write;

you need to call the function using UFCS (aka Universal Function Call Syntax):

std::io::Write::write_all(&mut f, b"Hello, world!")

More info at: http://doc.rust-lang.org/book/ufcs.html

I mark this as solved.