about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPyry Kontio <pyry.kontio@drasa.eu>2015-03-02 06:14:45 +0200
committerSteve Klabnik <steve@steveklabnik.com>2015-03-08 08:38:10 -0400
commit6dcc0e563118ef2d6d07b5d9d6d0f1042b497db0 (patch)
tree27318529a65c948d0dd2d5d6dbbe436796be425b
parentb2f09c1165db805ed00707257dd94bb309faf0fe (diff)
downloadrust-6dcc0e563118ef2d6d07b5d9d6d0f1042b497db0.tar.gz
rust-6dcc0e563118ef2d6d07b5d9d6d0f1042b497db0.zip
Adds an example for PhantomData<T>.
-rw-r--r--src/libcore/marker.rs40
1 files changed, 39 insertions, 1 deletions
diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs
index 868a671b956..a05bc04a530 100644
--- a/src/libcore/marker.rs
+++ b/src/libcore/marker.rs
@@ -351,7 +351,45 @@ pub trait PhantomFn<A:?Sized,R:?Sized=()> { }
 /// instance, it will behave *as if* an instance of the type `T` were
 /// present for the purpose of various automatic analyses.
 ///
-/// For example, embedding a `PhantomData<T>` will inform the compiler
+/// # Examples
+///
+/// When handling external resources over a foreign function interface, `PhantomData<T>` can
+/// prevent mismatches by enforcing types in the method implementations, although the struct
+/// doesn't actually contain values of the resource type.
+///
+/// ```
+/// # trait ResType { fn foo(&self); };
+/// # struct ParamType;
+/// # mod foreign_lib {
+/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
+/// # pub fn do_stuff(_: *mut (), _: usize) {}
+/// # }
+/// # fn convert_params(_: ParamType) -> usize { 42 }
+/// use std::marker::PhantomData;
+/// use std::mem;
+///
+/// struct ExternalResource<R> {
+///    resource_handle: *mut (),
+///    resource_type: PhantomData<R>,
+/// }
+///
+/// impl<R: ResType> ExternalResource<R> {
+///     fn new() -> ExternalResource<R> {
+///         let size_of_res = mem::size_of::<R>();
+///         ExternalResource {
+///             resource_handle: foreign_lib::new(size_of_res),
+///             resource_type: PhantomData,
+///         }
+///     }
+///
+///     fn do_stuff(&self, param: ParamType) {
+///         let foreign_params = convert_params(param);
+///         foreign_lib::do_stuff(self.resource_handle, foreign_params);
+///     }
+/// }
+/// ```
+///
+/// Another example: embedding a `PhantomData<T>` will inform the compiler
 /// that one or more instances of the type `T` could be dropped when
 /// instances of the type itself is dropped, though that may not be
 /// apparent from the other structure of the type itself. This is