# Is \`AsMut\<\[T\]\>\` stable across repeated calls?

**URL:** <https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258>\
**Category:** uncategorized\
**Created:** [October 26, 2026, 4:15am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258 "2026-10-26T04:15:57Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![olpa](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/olpa/32/48390_2.png) [@olpa](https://users.rust-lang.org/u/olpa)\
**Post date:** [October 26, 2026, 4:15am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/1 "2026-10-26T04:15:57Z")

</div>

Has anyone seen a real `AsMut<[T]>` implementation where repeated calls to `as_mut()` return slices with different addresses or lengths, even when no other `&mut self` method is called between them?

In other words, I expect this property:

> As long as no other `&mut self` method on the object is called between calls,  
> `as_mut()` always returns a slice with the same address and length.

I've looked at [https://doc.rust-lang.org/std/convert/trait.AsMut.html](https://doc.rust-lang.org/std/convert/trait.AsMut.html) and haven't found such a statement.

Here is an example of code that:

- relies on this contract, and
- fails with a valid but surprising `AsMut` implementation.

```rust
//! Minimal example: code that is generic over `AsMut<[u8]>` silently
//! assumes that `as_mut()` is a pure view of the object's state.

use std::panic::{catch_unwind, AssertUnwindSafe};

/// Fills a buffer with the letter `x`, one byte at a time.
/// The constructor remembers the length, and `pos` is the next free index.
struct Filler<B: AsMut<[u8]>> {
    buf: B,
    pos: usize,
    len: usize,
}

impl<B: AsMut<[u8]>> Filler<B> {
    fn new(mut buf: B) -> Self {
        let len = buf.as_mut().len();
        Self { buf, pos: 0, len }
    }

    fn is_full(&self) -> bool {
        self.pos == self.len
    }

    fn put_x(&mut self) {
        // A second `as_mut()` call: the stored `pos` and `len` are applied
        // to whatever slice it returns now.
        self.buf.as_mut()[self.pos] = b'x';
        self.pos += 1;
    }

    /// Fill the whole buffer with `x` and give it back.
    fn fill(mut self) -> B {
        while !self.is_full() {
            self.put_x();
        }
        self.buf
    }
}

/// Well-behaved: the same as `Vec<u8>`, `[u8; N]`, `Box<[u8]>`, ...
struct Stable([u8; 4]);

impl AsMut<[u8]> for Stable {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Switches between two buffers: `as_mut()` has a side effect.
struct Flip {
    a: [u8; 4],
    b: [u8; 4],
    flip: bool,
}

impl AsMut<[u8]> for Flip {
    fn as_mut(&mut self) -> &mut [u8] {
        self.flip = !self.flip;
        if self.flip {
            &mut self.a
        } else {
            &mut self.b
        }
    }
}

/// Returns a shorter slice after the first call.
struct Shrinking {
    data: [u8; 4],
    calls: usize,
}

impl AsMut<[u8]> for Shrinking {
    fn as_mut(&mut self) -> &mut [u8] {
        self.calls += 1;
        if self.calls == 1 {
            &mut self.data
        } else {
            &mut self.data[..2]
        }
    }
}

fn main() {
    let mut stable = Filler::new(Stable([0; 4])).fill();
    println!("stable: {:?}", stable.as_mut());

    // No panic, but the bytes are scattered over two buffers.
    let flip = Filler::new(Flip { a: [0; 4], b: [0; 4], flip: false }).fill();
    println!("flip: a={:?} b={:?}", flip.a, flip.b);

    // Panics: index out of range, `len` is 4 but the slice has 2 bytes.
    let result = catch_unwind(AssertUnwindSafe(|| {
        Filler::new(Shrinking { data: [0; 4], calls: 0 }).fill();
    }));
    println!("shrinking: panicked = {}", result.is_err());
}

```

Running:

```plaintext
stable: [120, 120, 120, 120]
flip: a=[0, 120, 0, 120] b=[120, 0, 120, 0]

thread 'main' (456197) panicked at adversarial_asmut.rs:27:9:
index out of bounds: the len is 2 but the index is 2
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
shrinking: panicked = true

```

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [October 26, 2026, 5:25am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/2 "2026-10-26T05:25:10Z")

</div>

Your example shows that relying on such a property for soundness is clearly incorrect. And you've already determined that the documentation doesn't say it's logically necessary.

So what else are you looking for, exactly?

---

<div class="post-metadata">

**Author:** ![programmerjake](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/programmerjake/32/12342_2.png) [@programmerjake](https://users.rust-lang.org/u/programmerjake)\
**Post date:** [October 26, 2026, 6:40am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/3 "2026-10-26T06:40:02Z")

</div>

> [@olpa](#):
>
> Has anyone seen a real `AsMut<[T]>` implementation where repeated calls to `as_mut()` return slices with different addresses or lengths, even when no other `&mut self` method is called between them?

[technically yes](https://play.rust-lang.org/?version=stable&mode=release&edition=2024&gist=6b02e27e208df6f12a97e81c20174533):

```rust
fn main() {
    let mut value = &mut [String::new()];
    let slice: &[String] = value.as_mut();
    println!("{slice:p}");
    let mut other_array = [String::new()];
    value = &mut other_array;
    let slice: &[String] = value.as_mut();
    // prints a different address even though we didn't call
    // any `&mut` methods other than `as_mut()` itself.
    println!("{slice:p}");
}

```

---

<div class="post-metadata">

**Author:** ![olpa](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/olpa/32/48390_2.png) [@olpa](https://users.rust-lang.org/u/olpa)\
**Post date:** [October 26, 2026, 11:46am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/4 "2026-10-26T11:46:56Z")

</div>

> Your example shows that relying on such a property for soundness is clearly incorrect. And you've already determined that the documentation doesn't say it's logically necessary.
> 
> So what else are you looking for, exactly?

As sole mind, I can't understand what's wrong here: is `AsMut` under-specified because the expected behavior is so obvious that authors didn't even consider the adversarial behavior, or if I'm wrong about expected behavior.

I need the swarm intelligence to help to decide.

For now, I'm 99% for under-specification case. My sample `AsMut` implementations are clearly adversarial.

But there is still 1% that I'm overlooking a reasonable `AsMut` that doesn't fit to the desired contract. This is an open challenge, to find such.

> ```rust
> value = &mut other_array;
> ...
> // prints a different address even though we didn't call
> // any `&mut` methods other than `as_mut()` itself.
> 
> ```

But we replaced `value` completely, it's another object.

---

<div class="post-metadata">

**Author:** ![akrauze](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/akrauze/32/39129_2.png) [@akrauze](https://users.rust-lang.org/u/akrauze)\
**Post date:** [October 26, 2026, 12:07pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/5 "2026-10-26T12:07:15Z")

</div>

The only possible use case I can think of for `AsMut<[T]>` returning stable address would be unsafe code. And since `AsMut` is not an `unsafe` trait, general rule that unsafe code shall never rely on safety invariants being upheld by safe code, should be used.

---

<div class="post-metadata">

**Author:** ![farnz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/farnz/32/14366_2.png) [@farnz](https://users.rust-lang.org/u/farnz)\
**Post date:** [October 26, 2026, 2:03pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/6 "2026-10-26T14:03:43Z")

</div>

> [@olpa](#):
>
> As sole mind, I can't understand what's wrong here: is `AsMut` under-specified because the expected behavior is so obvious that authors didn't even consider the adversarial behavior, or if I'm wrong about expected behavior.

It'll be underspecified because most programs aren't adversarial.

In Rust, we tend not to care about adversarial trait implementation unless we're working with `unsafe` - in Safe Rust, the worst case that can happen due to an adversarial implementation is a logic bug, and we consider that the fault of the adversarial implementation, not the fault of the consumer.

Unsafe Rust flips that, to an extent; the `unsafe` superpowers allow you to have "spooky action at a distance", and so any time a trait implementation is relevant to your `unsafe` code, you need to assume that it's adversarial, but compliant with its safety guarantees if it includes `unsafe` itself.

In the case of `AsMut`, there are adversarial implementations that don't require `unsafe` internally, and so `unsafe` Rust can't depend on any arbitrary `impl AsMut` to be friendly - but safe Rust can (logic bug), and you can also depend on specific `impl AsMut` to be safe (e.g. you can depend on `Vec`, `String` and `[T; N]` implementations of `AsMut`, but not on arbitrary user-supplied `AsMut`).

---

<div class="post-metadata">

**Author:** ![khimru](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/khimru/32/31344_2.png) [@khimru](https://users.rust-lang.org/u/khimru)\
**Post date:** [October 26, 2026, 4:47pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/7 "2026-10-26T16:47:42Z")

</div>

> [@akrauze](#):
>
> And since `AsMut` is not an `unsafe` trait, general rule that unsafe code shall never rely on safety invariants being upheld by safe code, should be used.

Safety invariants wouldn't be upheld by arbitrary safe code, but, of course, you can mark some “known safe” implementation with the marker trait (either sealed or `unsafe`) and use these.

This is typical example of how Rust discussions waste everyone's time: usually programming experts who know other languages go ten step from “business case” where step 4 or step 5 is totally illogical and not permitted in Rust (like here: writing `unsafe` code that relies on some other arbitrary safe code that implements safe trait) and then faces problem at step 10. Then step 10 is presented without any history… this leads to week-long discussions and very often “other language expert” feels so strongly about the fact that step 4 have to be done in the exact way s/he likes (and not in a way compatible with Rust) that the whole discussion becomes pointless.

So… what are you **actually** trying to do that you need that question answered?

---

<div class="post-metadata">

**Author:** ![miro](https://avatars.discourse-cdn.com/v4/letter/m/f08c70/32.png) [@miro](https://users.rust-lang.org/u/miro)\
**Post date:** [October 27, 2026, 1:36am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/8 "2026-10-27T01:36:55Z")

</div>

- Unsafe code can't assume safe traits are implemented correctly, but safe code usually can.
- The trait doesn't say the returned address is stable, so it may not always be stable
- There's likely a implementation somewhere that has a genuine reason to change address and length upon repeated calls (e.g. if the value is behind a pointer that's atomically swapped with a different pointer by another thread)

---

<div class="post-metadata">

**Author:** ![olpa](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/olpa/32/48390_2.png) [@olpa](https://users.rust-lang.org/u/olpa)\
**Post date:** [October 27, 2026, 12:07pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/9 "2026-10-27T12:07:01Z")

</div>

Good catch.

> So… what are you **actually** trying to do that you need that question answered?

I have a code conceptually similar to `Filler`. The code doesn't pass the code review because the reviewer (who is an AI agent) questions its correctness.

I shut it up by saying I know what I'm doing, but actually it's not the case. The finding is absolutely valid, and considering I'm writing a foundational code I have to address it. I had no idea what to do and hoped the swarm intelligence would help.

Yes. Now I know the answer.

The mentioning of unsafe and addresses looked wrong for me, but they helped to understand what does the code expect actually:

It is equality. All the code wants is that stored indexes and written bytes are still valid between calls.

Here is a sort of proof:

- At time T1, the object contains the value v1.
- After AsMut, the value m1 is equivalent to v1. (Should be postulated as an exiom.)
- At time T2, the object contains the value v2. Because we didn't do mutable operations, v2 is equivalent to v1.
- After AsMut, the value m2 is equivalent to v2.
- By transitivity, m1 is equivalent to m2, exactly what the code expects.

I've reduced my need of a contract to two axioms, which don't need a proof. Internal mutability would break the second axiom, but it's a topic for another day.

---

<div class="post-metadata">

**Author:** ![miro](https://avatars.discourse-cdn.com/v4/letter/m/f08c70/32.png) [@miro](https://users.rust-lang.org/u/miro)\
**Post date:** [October 27, 2026, 1:36pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/10 "2026-10-27T13:36:58Z")

</div>

Well you can add a new trait, maybe call it `AsMutStable<T>` that has the guarantees you want, `AsMut<T>` as a supertrait, and no methods,  
implement it for applicable std types,  
and now make the assumptions you wanted to make in safe code as long as the type implements `AsMutStable<T>`

---

<div class="post-metadata">

**Author:** ![khimru](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/khimru/32/31344_2.png) [@khimru](https://users.rust-lang.org/u/khimru)\
**Post date:** [October 27, 2026, 2:21pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/11 "2026-10-27T14:21:16Z")

</div>

> [@olpa](#):
>
> I have a code conceptually similar to `Filler`.

Looks more similar to `HashSet`, if you will ask me.

And the HastSet supports [the following invariant in that case](https://doc.rust-lang.org/std/collections/struct.HashMap.html); _The behavior resulting from either logic error is not specified, but will be encapsulated to the `HashMap` that observed the logic error and not result in undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and non-termination._

I recommend to consider similar restriction: make sure your code crashes in suitably visible way if given “bad” type, but ensure that there are no undefined behavior.

---

<div class="post-metadata">

**Author:** ![marlez](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/marlez/32/52182_2.png) [@marlez](https://users.rust-lang.org/u/marlez)\
**Post date:** [October 27, 2026, 7:39pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/12 "2026-10-27T19:39:08Z")

</div>

For my own sanity's sake: when talking about the "sole mind", the "AI reviewer" of yours, as well as the "swarm intelligence" you've alluded to several times now; are you speaking.. ironically?

As for the love of me, I'm having an extremely hard time processing the exact train of thought that might lead someone to so openly (if not brazenly) reduce the whole of the _people_ inhabiting this forum, into some AI-rotten marketing-speak garbage like "swarm intelligence"; before asking for a chunk of their _personal_ time, effort, knowledge, and experience to help you with an "issue" your token auto-completion LLM-wit (do these qualify as "intelligent" now?) pointed out for you.

The `AsMut` is a `trait`. A compile-time construct, erased entirely by the time your code ever gets a chance to run. The only method, whose existence the compiler is enforcing via the resolution of the type/trait system itself, is a plain `fn as_mut(self: &mut [T])`. It doesn't provide _any_ way to guarantee that a given function pointer upholds any given contract: be it stability-wise or not.

Doing so would go against the "zero-cost abstraction" philosophy the language does its best to deliver, for one. No amount of documention-level "statements" per se can guarantee anything of the sort, for two. What is and isn't "obvious" and "adversarial" is as much a matter of personal preference as it is of opinion. I wouldn't be surprised if anyone ever writes something akin to:

```rust
use std::convert::{AsMut, AsRef};
use std::time::SystemTime as Time;

pub struct LastMut {
    inner: Vec<Time>,
}

impl LastMut {
    pub fn new() -> Self {
        let inner = Vec::new();
        Self { inner }
    }
    pub fn record(&mut self) {
        self.inner.push(Time::now());
    }
}

impl AsRef<[Time]> for LastMut {
    fn as_ref(&self) -> &[Time] {
        &self.inner
    }
}

impl AsMut<[Time]> for LastMut {
    fn as_mut(&mut self) -> &mut [Time] {
        self.record();
        &mut self.inner
    }
}

```

Every use-case is different. None gets a definite say on what is and isn't "expected" and/or "under/over-specified". Your "AI reviewer" has neither the "taste" nor any amount of any quality _remotely_ approaching the human kind of "intelligence" to differentiate a bold-albeit-controversial choice you might yet have to make going forward; from a choice that doesn't align nearly as well with the bell-curve distribution of syntax comprising the data set it's been trained on. Both will be "wrong", and both will get "corrected" into the mindless, soulless, and statistically average.

On the side note: have you written enough Rust yourself up to this point, to be able to properly judge your AI reviewer's happy-go-lucky advice, to begin with? Or shall the "swarm intelligence" have to handle that for you as well, once your LLM advisor has given their final seal of approval?

---

<div class="post-metadata">

**Author:** ![jumpnbrownweasel](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/jumpnbrownweasel/32/17403_2.png) [@jumpnbrownweasel](https://users.rust-lang.org/u/jumpnbrownweasel)\
**Post date:** [October 27, 2026, 8:53pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/13 "2026-10-27T20:53:30Z")

</div>

If it helps, I believe @farnz [answered](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/6) your question thoroughly. In short, if you're not relying on this stability in unsafe code, then worrying about it should be unnecessary -- bad trait implementations will give bad behavior, i.e., logic bugs, but will not cause UB. If you think the stability is necessary, please explain why.

---

<div class="post-metadata">

**Author:** ![simonbuchan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/simonbuchan/32/19939_2.png) [@simonbuchan](https://users.rust-lang.org/u/simonbuchan)\
**Post date:** [October 27, 2026, 9:47pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/14 "2026-10-27T21:47:38Z")

</div>

> [@khimru](#):
>
> This is typical example of how Rust discussions waste everyone's time

To be fair, this is only because the overwhelming majority of the time in other languages the discussion is simply never held at all: UB is an explanation for why a bug happened, not a problem to prevent before it becomes a bug.

Consider the equivalent discussion for an equivalent C++ pure virtual base class: I'm pretty sure the discussion would be essentially just arguing the semantics of what documentation even means, saying you should test your code with all implementations, or just a shrug "nothing is guaranteed"

At least in Rust the expectations are clear enough you can get a straightforward "you're exposing yourself to breaking changes in non-breaking version changes if you are depending on behavior that is not documented to be guaranteed" and a further warning that "for the purpose of unsafe code, safe traits don't guarantee anything other than a lack of UB, you need unsafe traits for that"

---

<div class="post-metadata">

**Author:** ![olpa](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/olpa/32/48390_2.png) [@olpa](https://users.rust-lang.org/u/olpa)\
**Post date:** [October 28, 2026, 4:45am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/15 "2026-10-28T04:45:49Z")

</div>

> the "AI reviewer" ...

A detailed response to the statements around that could start a flame discussion, so let's skip it. If "AI" is uncomfortable, let's call it a "theorem prover" or a "formal verifier".

Meanwhile, I stumbled upon a similar topic with a similar lack of a concrete conclusion: "Are AsRef and Borrow supposed to be deterministic?", [Are AsRef and Borrow supposed to be deterministic? - libs - Rust Internals](https://internals.rust-lang.org/t/are-asref-and-borrow-supposed-to-be-deterministic/17829)

Thanks everyone for sharing thoughts! It was an interesting exercise to follow them.

---

<div class="post-metadata">

**Author:** ![farnz](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/farnz/32/14366_2.png) [@farnz](https://users.rust-lang.org/u/farnz)\
**Post date:** [October 28, 2026, 9:20am UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/16 "2026-10-28T09:20:44Z")

</div>

And if you're in a "correct code through documentation" environment, `Filler`'s documentation can explain what it requires from `B`'s `AsMut<[u8]>` implementation, so that if a consumer of `Filler` provides an adversarial implementation, you can point to the documentation and say "that's your logic bug".

---

<div class="post-metadata">

**Author:** ![mattfbacon](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mattfbacon/32/24751_2.png) [@mattfbacon](https://users.rust-lang.org/u/mattfbacon)\
**Post date:** [October 28, 2026, 9:57pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/17 "2026-10-28T21:57:10Z")

</div>

[stable\_deref\_trait - Rust](https://docs.rs/stable_deref_trait) seems related

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [October 28, 2026, 10:08pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/18 "2026-10-28T22:08:03Z")

</div>

[Be careful.](https://github.com/Storyyeller/stable_deref_trait/issues/15)

---

<div class="post-metadata">

**Author:** ![miro](https://avatars.discourse-cdn.com/v4/letter/m/f08c70/32.png) [@miro](https://users.rust-lang.org/u/miro)\
**Post date:** [November 7, 2026, 7:42pm UTC](https://users.rust-lang.org/t/is-asmut-t-stable-across-repeated-calls/143258/19 "2026-11-07T19:42:59Z")

</div>

> [@marlez](#):
>
> to so openly (if not brazenly) reduce the whole of the _people_ inhabiting this forum, into some AI-rotten marketing-speak garbage like "swarm intelligence"

It may also be reducing us to a swarm of birds, boids, or even protozoa, so it does not necessarily have anything to do with AI.
