External Publication
Visit Post

Semantic of smart pointers

Rust Internals [Unofficial] May 19, 2026
Source

"Smart pointer" is an individual concept in The Rust Programming Language book. However, I didn't find a semantic-level definition of what "smart pointer" is. Should there be some traits in core/std to provide this semantic?

This question arises from another question (How to constrain types where AsRef and AsMut point to the same data? - help - The Rust Programming Language Forum) I posted in the users forum:

When a function requires a smart pointer over a specific type, how to express this constraint?

I guess this scenario is common? In my code, I often require a smart pointer to [u8] buffer, which enables me to access and modify the buffer's data (without appending or removing the buffer). Discussion of the problem: whether the code patterns that require a smart pointer is common, is also very welcome

I was thinking of an unsafe trait (also suggested by others in the users forum post):

/// # SAFETY
///
/// Implementors should make sure the .as_ref() and .as_mut() returns the same data
unsafe trait AsData<T>: AsRef<T> + AsMut<T> {}

However, the correctness requirement in "SAFETY" section is still too weak to describe a smart pointer (which is also pointed out in the users forum post). The requirement only states that as_ref and as_mut return the same data, but there is no requirement of temporal consistency: the pointed data address should never change unless we deliberately replace it through as_mut. This is to prevent the implementors to randomly return different pointers in each invocations. I thought this is something like the DerefPure trait. This requirement is hard to express correctly, since what will happen if the smart pointer is a Vec and it reallocates?

So I suggest we shall discuss the semantic of smart pointers in Rust, and is it desirable to add some related trait to the core/std to express the semantic in type system?

Discussion in the ATmosphere

Loading comments...