@@ -351,7 +351,45 @@ pub trait PhantomFn<A:?Sized,R:?Sized=()> { }
351
351
/// instance, it will behave *as if* an instance of the type `T` were
352
352
/// present for the purpose of various automatic analyses.
353
353
///
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
355
393
/// that one or more instances of the type `T` could be dropped when
356
394
/// instances of the type itself is dropped, though that may not be
357
395
/// apparent from the other structure of the type itself. This is
0 commit comments