Confusion around sharing State
using with_state and Arc
(part 2 2025 edition?)
#3252
-
SummaryPartial resurrection of this issue from 2022. I was browsing the docs and I noticed the section on the main page of the docs that discusses sharing state all use Searching which one to use lead me to the 2022 github issue and I share the same/similar confusion around where to use Thanks you! axum version0.8.1 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The state must be It's important to realize that each handler will get a new clone of the state. So if you use a custom struct where you make deep copies, the handlers can't update the data for later handler calls. That (along with cloning Does that clear things up for you? Do you have any suggestions on how to improve the documentation? |
Beta Was this translation helpful? Give feedback.
The state must be
Clone
, axum doesn't really care if it'sArc
,AppState
where you manually implementClone
or eveni32
.It's important to realize that each handler will get a new clone of the state. So if you use a custom struct where you make deep copies, the handlers can't update the data for later handler calls. That (along with cloning
Arc
s being generally cheap) is why in most use cases you would use anArc
for state.Does that clear things up for you? Do you have any suggestions on how to improve the documentation?