Skip to content

Lifetime troubles #1341

Closed
Closed
@ViktorWb

Description

@ViktorWb

Hi! I've been stuck on an issue for a while and can't figure out what's causing it. Not sure if there's an issue in ndarray, Rust or if I'm just missing something.

Playground

I'm trying to create a struct containing a list of arrays, where the array elements are string slices:

struct ListOfArrays<'a, D: ndarray::Dimension> {
    data: &'a [ndarray::Array<&'a str, D>],
}

fn does_not_work() {
    let arrays = [ndarray::array![""]];
    let list = ListOfArrays { data: &arrays };
}
// Error: `arrays` does not live long enough
// borrowed value does not live long enough. 
// `arrays` dropped here while still borrowed

Thing is, this same thing is totally doable with other Rust structs, for example if we replace ndarray with Vec:

struct ListOfArraysVec<'a> {
    data: &'a [Vec<&'a str>],
}

fn works() {
    let arrays = [vec![""]];
    let list = ListOfArrays { data: &arrays };
}
// Compiles!

I don't understand why this happens with ndarray, and I haven't been successful in recreating the issue with any struct other than ndarray, so that is why I'm posting here. Any guidance would be much appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions