# Why are Julia strings immutable?

**URL:** <https://discourse.julialang.org/t/why-are-julia-strings-immutable/117320>\
**Category:** Internals & Design\
**Tags:** strings\
**Created:** [July 22, 2024, 2:24am UTC](https://discourse.julialang.org/t/why-are-julia-strings-immutable/117320 "2024-07-22T02:24:11Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [July 22, 2024, 2:51am UTC](https://discourse.julialang.org/t/why-are-julia-strings-immutable/117320/2 "2024-07-22T02:51:35Z")

</div>

See the explanation here: [Why are strings immutable (historical records request)](https://discourse.julialang.org/t/why-are-strings-immutable-historical-records-request/92115)

> Julia doesn’t implement strings as arrays of characters

It doesn’t, it implements them internally as arrays of _bytes_ in a UTF-8 encoding (but this internal array is hidden in Julia internals so that you cannot mutate it). This means that ASCII characters take only 1 byte per character, but other Unicode characters may take 2–4 bytes. In contrast, implementing strings as arrays of _characters_ would take 4 bytes for _every_ character for not much practical benefit.

(You might object that arrays of characters would allow you to query the n-th character quickly, or substitute one character for another in-place, but these operations turn out to be not so useful as you might think in practice, in part because Unicode is much more complicated than most people realize. See also [utf8everywhere.org](https://utf8everywhere.org/) for more discussion of string encoding and why UTF-8 is a choice that many people have adopted.)

The StringViews.jl package implements an `AbstractString` type that is also UTF-8, but which can be backed by a _mutable_ array of bytes. With this type, one could conceivably implement an in-place `filter!` function on a `StringView`. (Deleting characters in-place during iteration is very straightforward in the UTF-8 encoding, despite the variable character width.)

(And, of course, it is perfectly possible to implement a new `AbstractString` subtype backed by an array of `Char`. The LegacyStrings.jl package includes a related string type in the UTF-32 encoding, which is an array of Unicode characters identified by codepoint. It’s not something that seems to get much practical usage, however.)

---

_[View the full topic](https://discourse.julialang.org/t/why-are-julia-strings-immutable/117320)._
