Skip to content

Added documentation for relaxing trait bounds on PhatomData #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions doc/PhantomData.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# PhantomData
[PhantomData](https://doc.rust-lang.org/std/marker/struct.PhantomData.html) implements all of the derivable traits without placing bounds on the type it is given. Because of this, if a generic type is only used in a `PhantomData`, no bounds are placed on it. This is in contrast to Rust's `derive` which will add the trait bound regardless.

## Example
This:
```rust
# extern crate derivative;
# use derivative::Derivative;
# use std::{marker::PhantomData, fmt::Debug};
#
# struct NonDebug ();
#
#[derive(Derivative)]
#[derivative(Debug(bound = "A: Debug"))] // bound not needed.
struct Foo<A, B> {
a: A,
b: PhantomData<B>,
}

fn main() {
let foo: Foo<usize, NonDebug> = Foo{ a: 1, b: PhantomData };
println!("{:?}", foo);
}
```

is equivalent to this:
```rust
# extern crate derivative;
# use derivative::Derivative;
# use std::{marker::PhantomData, fmt::Debug};
#
# struct NonDebug ();
#
#[derive(Derivative)]
#[derivative(Debug)]
struct Foo<A, B> {
a: A,
b: PhantomData<B>,
}

fn main() {
let foo: Foo<usize, NonDebug> = Foo{ a: 1, b: PhantomData };
println!("{:?}", foo);
}
```

Rust's derive which does not compile because it adds the bound `B: Debug`:
```rust, compile_fail
# use std::{marker::PhantomData, fmt::Debug};
#
# struct NonDebug ();
#
#[derive(Debug)] // This will added the bounds: A: Debug, B: Debug
struct Foo<A, B> {
a: A,
b: PhantomData<B>,
}

fn main() {
let foo: Foo<usize, NonDebug> = Foo{ a: 1, b: PhantomData };
println!("{:?}", foo); // Won't compile because NonDebug does not implement Debug.
}
```
1 change: 1 addition & 0 deletions doc/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@
<!-- * [Ignoring fields](cmp.md#ignoring-a-field) -->
<!-- * [Alternative comparison function](cmp.md#compare-with) -->
<!-- * [Custom bound](cmp.md#custom-bound) -->
* [PhantomData](PhantomData.md)