rust-lang / book

The Rust Programming Language
https://doc.rust-lang.org/book/
Other
15.28k stars 3.44k forks source link

Lacking explanation of mutable globals (static mut alternatives) #4104

Open kornelski opened 1 week ago

kornelski commented 1 week ago

In an error message about mutable global variables (https://github.com/rust-lang/rust/pull/133143) I wanted to link to the book to a chapter explaining how to use static with mutable data, but I couldn't find one.

The closest one is about Mutex, but the chapter is written in the context of channels and non-global shared mutable state, which doesn't work as a reference for how to use static X: Mutex.

Despite global variables not being the best practice, I think a chapter dedicated to use of mutable statics is needed. Without guidance, users may discover static mut, which is even more problematic. It's not obvious that an "immutable" static can be used for mutable globals. Rust now has a new OnceLock that works for initialization of globals.

chriskrycho commented 3 days ago

This is definitely an area the book doesn’t currently cover, and I am sympathetic to the need to document it. I don’t think we should add a chapter on it, though. The book is already arguably too long for the print version and we just added another 15K words (not counting code samples!) for async, so we have actually been looking for ways to make it shorter.

Even in its digital form, the structure is a bit unwieldy, because of another issue @carols10cents and I have talked about off and on since I came onto the project: The book ends up doing double duty as the official introduction to the language and the official documentation of the language, and those purposes are somewhat at odds. That is perhaps most apparent with the print edition, but I think it is true of even the digital edition. The kind of work that a book teaching the language has to do is very different from what pages documenting all aspects of a language from a user’s POV, which is different still again from what something like the reference is (it often verges into territory almost no user will ever care about, most useful for implementers and folks doing advanced library authoring).

Bluntly: We (meaning the Rust project) do not have a strategy for this, but we need one—precisely so we have a place to put things like this!

Even though I do not think we should add a chapter, I am leaving this open rather than closing it because I agree with the problem statement, and this is a(nother) helpful data point for trying to solve it.