Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use or cast a constructor as a fn

I want to write something like this:

use std::{iter, ops};

struct Idx(usize);

fn get_inds() -> iter::Zip<iter::Map<ops::RangeFrom<usize>, fn(usize) -> Idx>, ops::RangeFrom<usize>> {
    (0..).map(Idx).zip(0..)
}

However, this fails to compile:

error: mismatched types [--explain E0308]
 --> src/main.rs:6:9
6 |>         (0..).map(Idx).zip(0..)
  |>         ^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found fn item
note: expected type `std::iter::Zip<std::iter::Map<std::ops::RangeFrom<usize>, fn(usize) -> Idx>, std::ops::RangeFrom<usize>>`
note:    found type `std::iter::Zip<std::iter::Map<std::ops::RangeFrom<usize>, fn(usize) -> Idx {Idx::{{constructor}}}>, std::ops::RangeFrom<_>>`

I then cast the function:

fn get_inds() -> iter::Zip<iter::Map<ops::RangeFrom<usize>, fn(usize) -> Idx>, ops::RangeFrom<usize>> {
    (0..).map(Idx as fn(usize) -> Idx).zip(0..)
}

Which generates the following compiler warning. Why am I getting a warning? What is the proper way to use the constructor like this?

warning: can't cast this type, #[warn(const_err)] on by default
 --> src/main.rs:6:19
6 |>         (0..).map(Idx as fn(usize) -> Idx).zip(0..)
  |>                   ^^^^^^^^^^^^^^^^^^^^^^^
like image 937
dspyz Avatar asked Aug 20 '16 16:08

dspyz


1 Answers

It's a bogus warning caused by recent changes to the compiler's constant evaluator. See #33452, #33291, etc. I wouldn't worry about it, but it's worth submitting a bug to the Rust repo so it can be fixed.

like image 75
durka42 Avatar answered Nov 12 '22 13:11

durka42