Need some help to understand the behavior of Index trait on StringRecord #334
-
|
rust version: rustc 1.71.0 (8ede3aae2 2023-07-12) I don't know if I read the error message correctly, it seems that the index operator of Sample Code: It give the following error: I'm wondering if there is any explanation of this behavior (It's surprising that we can even return a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
The error is telling you what you should do: use This quirk tends to only apply to The docs for |
Beta Was this translation helpful? Give feedback.
The error is telling you what you should do: use
&header[0]instead ofheader[0]. The key here is thatheader[0]is actually syntactic sugar for*header.index(0). Since theIndeximpl forStringRecordreturns a&str, it follows that the type of*header.index(0)isstr. Sincestris a dynamically sized type, you get a compiler error here because the compiler doesn't know how much stack space to allocate fort.This quirk tends to only apply to
Indeximpls that return fat pointers, such as&str. In cases where theIndeximpl returns a regular pointer, say,&u8, thenslice[0]would just return au8which is typically what you want.The docs for
std::ops::Indexare a little sparse, but they m…