Skip to content

Commit 6dcc0e5

Browse files
golddrankssteveklabnik
authored andcommitted
Adds an example for PhantomData<T>.
1 parent b2f09c1 commit 6dcc0e5

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/libcore/marker.rs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,45 @@ pub trait PhantomFn<A:?Sized,R:?Sized=()> { }
351351
/// instance, it will behave *as if* an instance of the type `T` were
352352
/// present for the purpose of various automatic analyses.
353353
///
354-
/// For example, embedding a `PhantomData<T>` will inform the compiler
354+
/// # Examples
355+
///
356+
/// When handling external resources over a foreign function interface, `PhantomData<T>` can
357+
/// prevent mismatches by enforcing types in the method implementations, although the struct
358+
/// doesn't actually contain values of the resource type.
359+
///
360+
/// ```
361+
/// # trait ResType { fn foo(&self); };
362+
/// # struct ParamType;
363+
/// # mod foreign_lib {
364+
/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
365+
/// # pub fn do_stuff(_: *mut (), _: usize) {}
366+
/// # }
367+
/// # fn convert_params(_: ParamType) -> usize { 42 }
368+
/// use std::marker::PhantomData;
369+
/// use std::mem;
370+
///
371+
/// struct ExternalResource<R> {
372+
/// resource_handle: *mut (),
373+
/// resource_type: PhantomData<R>,
374+
/// }
375+
///
376+
/// impl<R: ResType> ExternalResource<R> {
377+
/// fn new() -> ExternalResource<R> {
378+
/// let size_of_res = mem::size_of::<R>();
379+
/// ExternalResource {
380+
/// resource_handle: foreign_lib::new(size_of_res),
381+
/// resource_type: PhantomData,
382+
/// }
383+
/// }
384+
///
385+
/// fn do_stuff(&self, param: ParamType) {
386+
/// let foreign_params = convert_params(param);
387+
/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
388+
/// }
389+
/// }
390+
/// ```
391+
///
392+
/// Another example: embedding a `PhantomData<T>` will inform the compiler
355393
/// that one or more instances of the type `T` could be dropped when
356394
/// instances of the type itself is dropped, though that may not be
357395
/// apparent from the other structure of the type itself. This is

0 commit comments

Comments
 (0)