This fascinating snippet of Rust does some tricky work with no allocations or copying, type- and memory-safely: gist.github.com/Aatch/5734372
Conversation
it at least allocates the Some() on line 59, right? Very cool, though.
1
Ah, sorry, I wasn’t counting stack allocations because they’re not what I normally worry about. Yes.
1
hm, how does that Some avoid being heap allocated? It gets returned from the get_string call. (I don't know Rust well).
1
The Some wraps a reference to an inner pointer of the json argument. The “lifetime parameters” ensure the safety of that trick.
1
right, that part I understood, and is very neat. But isn't the wrapper itself a new allocation?
2
It’s like this in C:
typedef union {
void *Some;
bool isNothing
} Option
Option foo(void *x) {
return (Option) {.Some = x}.
}
1
Replying to
(except much safer in a number of ways)
In that snippet, a structure is being returned on the stack, like the Option in my C.
Replying to
got it, thank you. Out of curiosity: does the compiler have special knowledge of Option, or is it library code?
1

