Skip to content

Specialization causes confilicting implementations with T and Option<T> #41140

Closed
@afonso360

Description

@afonso360

Trying to implement a specialization on type T of Option<T> causes the error E0119 stating that multiple implementations exist.

#![feature(specialization)]

use std::fmt;

trait ToFlag {
    fn format_flag(self, flag: char) -> String;
}

impl<T> ToFlag for T 
    where T: fmt::Display {
    default fn format_flag(self, flag: char) -> String {
        format!("-{} {}", flag, self)
    }
}

impl<T> ToFlag for Option<T> where T: fmt::Display {
    fn format_flag(self, flag: char) -> String {
        match self {
            Some(s) => s.format_flag(flag),
            None => "".to_string(),
        }
    }
}


fn main() {
    println!("std: {}", 1u32.format_flag('g'));
    println!("opt: {}", Some(1u32).format_flag('g'));
    println!("non: {}", None.format_flag('g'));
}

Expected output

std: -g 1
opt: -g 1
non: 

Actual output

The program fails to compile with

error[E0119]: conflicting implementations of trait `ToFlag` for type `std::option::Option<_>`:
  --> <anon>:16:1
   |
9  |   impl<T> ToFlag for T 
   |  _- starting here...
10 | |     where T: fmt::Display {
11 | |     default fn format_flag(self, flag: char) -> String {
12 | |         format!("-{} {}", flag, self)
13 | |     }
14 | | }
   | |_- ...ending here: first implementation here
15 | 
16 |   impl<T> ToFlag for Option<T> where T: fmt::Display {
   |  _^ starting here...
17 | |     fn format_flag(self, flag: char) -> String {
18 | |         match self {
19 | |             Some(s) => s.format_flag(flag),
20 | |             None => "".to_string(),
21 | |         }
22 | |     }
23 | | }
   | |_^ ...ending here: conflicting implementation for `std::option::Option<_>`

error: aborting due to previous error


Version Info

$ rustc --version --verbose
rustc 1.18.0-nightly (5e122f59b 2017-04-01)
binary: rustc
commit-hash: 5e122f59ba23494d460466cca53c71646d99c767
commit-date: 2017-04-01
host: x86_64-unknown-linux-gnu
release: 1.18.0-nightly
LLVM version: 3.9

Other Notes

This can potentially be a duplicate of #36587

playpen

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions