Skip to content

Need some help to understand the behavior of Index trait on StringRecord #334

Answered by BurntSushi
meretciel asked this question in Q&A
Discussion options

You must be logged in to vote

The error is telling you what you should do: use &header[0] instead of header[0]. The key here is that header[0] is actually syntactic sugar for *header.index(0). Since the Index impl for StringRecord returns a &str, it follows that the type of *header.index(0) is str. Since str is a dynamically sized type, you get a compiler error here because the compiler doesn't know how much stack space to allocate for t.

This quirk tends to only apply to Index impls that return fat pointers, such as &str. In cases where the Index impl returns a regular pointer, say, &u8, then slice[0] would just return a u8 which is typically what you want.

The docs for std::ops::Index are a little sparse, but they m…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@meretciel
Comment options

Answer selected by meretciel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants