rust-derivative icon indicating copy to clipboard operation
rust-derivative copied to clipboard

Weird behaviors of `format_with`

Open magiclen opened this issue 6 years ago • 1 comments

#[macro_use]
extern crate derivative;

#[derive(Derivative)]
#[derivative(Hash, PartialEq)]
pub struct A {
    #[derivative(Hash(hash_with = "std::hash::Hash::hash"), PartialEq(compare_with = "std::cmp::PartialEq::eq"))]
    v: u64
}

The above code can be compiled successfully while the following code can't

#[macro_use]
extern crate derivative;

#[derive(Derivative)]
#[derivative(Debug)]
pub struct A {
    #[derivative(Debug(format_with = "std::fmt::Debug::fmt"))]
    v: u64
}

However, if the struct uses generics,

#[macro_use]
extern crate derivative;

#[derive(Derivative)]
#[derivative(Debug)]
pub struct A<T: std::fmt::Debug> {
    #[derivative(Debug(format_with = "std::fmt::Debug::fmt"))]
    v: T
}

then it can be compiled.

I don't know why the format_with meta of the Debug attribute can be used only when the field type is generic.

The other weird thing is, when using generics, hash_with and compare_with don't need explicit trait binding.

#[macro_use]
extern crate derivative;

#[derive(Derivative)]
#[derivative(Hash, PartialEq)]
pub struct A<T> {
    #[derivative(Hash(hash_with = "std::hash::Hash::hash"), PartialEq(compare_with = "std::cmp::PartialEq::eq"))]
    v: T
}

The above code can be compiled successfully while the following code can't

#[macro_use]
extern crate derivative;

#[derive(Derivative)]
#[derivative(Debug)]
pub struct A<T> {
    #[derivative(Debug(format_with = "std::fmt::Debug::fmt"))]
    v: T
}

magiclen avatar Jul 22 '19 19:07 magiclen

The first issue is fixed in 1.0.3. The second issue might be a breaking change to fix.

mcarton avatar Aug 31 '19 19:08 mcarton