move icon indicating copy to clipboard operation
move copied to clipboard

[Feature Request] Add support for vector<&T> as function return

Open qiwihui opened this issue 3 years ago • 3 comments

🚀 Feature Request

Motivation

I would like to query a vector in a module with some filters, which return another vector with the same or less items in it. Is it possible to return vector<&T> without modifying the original vector. The following demo code contains errors.

public fun get<T: store>(container: &vector<T>): vector<&T> {
        let items = vector<&T>[];
        if (vector::length(container) != 0) {
            let container_len = vector::length<T>(container);
            let i = 0;
            while (i < container_len) {
                let item = vector::borrow(container, i);
                vector::push_back<T>(&mut items, item);
                i = i + 1;
            }
        };
        items
    }

Pitch

Describe the solution you'd like

Describe alternatives you've considered

Are you willing to open a pull request? (See CONTRIBUTING)

Additional context

qiwihui avatar Aug 10 '22 08:08 qiwihui

Can you simplify the example code, and make the code more useful and like a slice usage?

jolestar avatar Aug 10 '22 11:08 jolestar

Move does not support storing references inside structs or vectors. Doing so would require significant changes to the borrow checker that would need to be carefully designed and implemented

sblackshear avatar Aug 10 '22 16:08 sblackshear

Doing so would require significant changes to the borrow checker that would need to be carefully designed and implemented

Yeah if we want full-fledged support for references in structs or vectors then we'll likely need something like Rust's lifetime annotations. Although I heard @tnowacki was thinking about this issue or at least planning to relax the borrow checker a bit?

vgao1996 avatar Aug 18 '22 22:08 vgao1996