How to put a &[&str] into a struct?

I'm using GDAL package, which has a structure:

#[derive(Debug, Default)]
pub struct DatasetOptions<'a> {
    pub open_flags: GdalOpenFlags,
    pub allowed_drivers: Option<&'a [&'a str]>,
    pub open_options: Option<&'a [&'a str]>,
    pub sibling_files: Option<&'a [&'a str]>,
}

Trying to instantiate it, I can't create these Option<...str> members:

allowed_drivers: Some("GPKG"))

error: src/main.rs:6: expected slice `[&str]`, found `str`
note: src/main.rs:6: expected reference `&[&str]`

Googling for two hours produced some SO questions and answers (1, 2, 3, none of which made this code compile.

&*"GPKG".to_owned(),, &"GPKG"[..], and other ways all produce the same compilation error:

error: src/main.rs:6: expected slice `[&str]`, found `str`
note: src/main.rs:6: expected reference `&[&str]`
   found reference `&str`

What's the way to work around this?

Example Cargo.toml:

[package]
name = "sometest"
version = "0.1.0"
edition = "2018"

[dependencies]
gdal = "0.11"

Example main.rs:

use gdal::{Dataset, DatasetOptions, GdalOpenFlags};

fn main() {
	let dso = DatasetOptions {
		open_flags: GdalOpenFlags::GDAL_OF_UPDATE,
		allowed_drivers: Some(&"GPKG"[..]),
		open_options: None,
		sibling_files: None
	};
}
1 Like

Creating a variable and trying to get a reference to a slice didn't work.

let x = &"GPKG"[..];

allowed_drivers: Some(&((&x)[..])),
src/main.rs:7: expected slice `[&str]`, found `str`

If they're all literals:

	let dso = DatasetOptions {
		open_flags: GdalOpenFlags::GDAL_OF_UPDATE,
		allowed_drivers: Some(&["GPKG"]),
		open_options: None,
		sibling_files: None
	};

As

2 Likes

This worked, thanks! But what did the function expect, a slice of a str or a slice of array/vec of str?

It's a simple type mismatch. The allowed_drivers field has type &[&str] (inside the Option), which is a slice of string slices. You were trying to put a &str, i.e. just a string slice into it.

No, it wasn't a typo, I was familiar with this syntax ([T]), but thought in this case that it had to be a slice of a single string, not a slice of strings. :slight_smile:

I'm not sure what you mean by that. A single-element slice and a multi-element slice has the same type. But the original error resulted from the fact that you didn't provide a string of slices, you provided a string. That is not the same as a single-element slice of strings.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.