Ben Chuanlong Du's Blog

It is never too late to learn.

Generic and Specialization in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. There are 2 specialization related features specialization and min_specialization in Rust. Both of them are unstable currentlly. min_specialization implements only a subset of specialization but is more stable. It is suggested that you use min_specialization as specialization is disabled by Rust at this time. Eventually, min_specialization will be replace by specialization (after the implementation of specialization stablize).

  2. Specialization (unstable feature) is not powerful enough. It does not support specializing a generic function directly but you have to do it via specilizing a method of a trait. For more discussionss, please refer to Specialization of a simple function .

In [ ]:
#![feature(min_specialization)]

pub trait Compare<T : ?Sized = Self> {
    fn equal(&self, other: &T) -> bool;
}

default impl<T: ?Sized> Compare<T> for T where T: std::cmp::PartialEq<T> {
    fn equal(&self, other: &T) -> bool {
        self == other
    }
}
In [ ]:
#![feature(min_specialization)]

struct Special
{
    x : usize,
    y : usize
}

trait MyTrait
{
    fn myfunc(&self);
}

impl<T> MyTrait for T
{
    default fn myfunc(&self) { println!("hi"); }
}

impl MyTrait for Special
{
    fn myfunc(&self) { println!("I'm special"); }
}

fn main() {
    let spe = Special{
        x: 1,
        y: 2,
    };
    spe.myfunc();
}
In [ ]:

Comments