json icon indicating copy to clipboard operation
json copied to clipboard

Why does `serde_json::Value::as_array` return `Option<&Vec<Value>>` instead of `Option<&[Value]>`?

Open Logarithmus opened this issue 2 years ago • 3 comments

The question is in the title. It would be consistent with as_str which returns Option<&str>

Logarithmus avatar Jul 19 '22 10:07 Logarithmus

Because in the case of Option<&str> it returns a pointer to a chunk of then original JSON doc (which is a giant string), it's a freebie, whereas you can't return a slice/ref to value because the actual value it points to drops once the function returns

DanielJoyce avatar Aug 08 '22 20:08 DanielJoyce

Because in the case of Option<&str> it returns a pointer to a chunk of then original JSON doc (which is a giant string)

That is not true. We're talking about serde_json::Value, which is an owned type and does not point into the original JSON string. as_str returns a reference to the entire String stored in Value::String(), it would very well be able to return &String.


This would be a no-brainer change, except it breaks API. I guess for such a tiny issue, breakage is not justified

kangalio avatar May 23 '23 17:05 kangalio

A reasonable explanation is that .as_array_mut() has to return Option<&mut Vec<Value>>, so .as_array() should be consistent with that, more than it needs to be consistent with .as_str().

Regardless, I suggest this to be closed, breaking the API is a no-go.

marcospb19 avatar Jun 28 '23 04:06 marcospb19