Reason for putting index first and then the value in a vector insert?

Hey there,

I just want to know what is the reason for designing the vector insert functionality in such a way that first it takes the index and then takes the value like this:

vec_data.insert(index_number, actual value);

Why not make it opposite, like first insert the value at a certain index that is given below. This seemed natural to me as compared to the functionality that Rust has implemented.

vec_data.insert(actual value, index_number);

Let me know the reason behind it.

I don't think there was much discussion about the ordering of arguments of Vec::insert. It was first implemented in #12253 (11 years ago) and then stabilised with the current signature. Maybe you find this ordering unintuitive, because you are accustomed to a programming language where this is the case? I don't find putting the value before the index more intuitive. In a hash map, you insert(key, value), not insert(value, key). In an index expression vec[index] = value, the index also comes before the value.

7 Likes

As far as the hashmap is concerned, I know that the key should be written first but I am talking about the vector where in the insert functionality, I need to put the index first and then value.

But I don't know. Maybe you're right that I am used to it. But I found the value and then the index number more natural for myself.

The index is the key in a Vec.

5 Likes

With this mindset of taking the index as a key, it becomes easy to understand.

Aside from mimicking the index operator, as mentioned above, it's generally more ergonomic for API users to list function arguments from shortest to longest at the call site. In particular, the key (or index) argument is typically shorter than the value argument:

foo.insert(
    123, // key
    some
        .loooong()
        .multiline()
        .expression()
        .constructor(),
)
2 Likes

I thought that maybe multiple values are going to inserted in a vector using one .insert functionality but I don't think that it is possible using one .insert.

It requires multiple inserts to be written.

But yeah, generally the keys are less in length as compare to the values.