Creation of Non-linear types in Rust

Let's go with the simplest definitions of affine and linear types: affine meaning value of such type can be used at most once and linear meaning value of such type must be used exactly once.

Question: Can I create a non-linear type that can be used at most N times where N is an usize?

Use case: (roughly speaking)

Note: Zeroize is a trait that zeros out a value when it is dropped. MEC stands for 'max exposed count' and EC stands for 'exposed count'.


  1. At compile time, if a Secret if MEC == EC, then it is not possible to call expose_secret(...) -> &T. Perhaps using the typestate pattern.

Draft Implementation:

struct Secret<T: ?Sized + Zeroize, const MEC: usize, const EC: usize=0> { /* private fields */ }

Yes but it's extremely annoying: make every use by-value (i.e. affine) and return the same type with EC increased by one. You can't do this with just simple operations on the consts, you have to use emulation tricks like are done by the typenum crate.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.