Box::new + &[…] notation

master
Y 2019-11-17 16:50:48 +01:00
parent b2adb834d4
commit 9029b18fc0
1 changed files with 36 additions and 13 deletions

View File

@ -1,5 +1,20 @@
## setup
In module `common`, I have:
```rust
pub enum Value {
Bool(bool),
Str(String),
Int(isize),
Date(DateTime<chrono::Utc>)
}
pub type Record<'a> = HashMap<&'a str, Value>;
```
(in a future version, `Value` will probably become recursive, with a variant `Vec<Value>` for example)
In module `modules`, I have:
```rust
@ -34,35 +49,43 @@ struct Available {
cons: Box<fn(ModuleArgs) -> dyn Module>
}
const available: [Available] = [
Available { name: "equals", cons: Box.new(filters::Equals::from_args) }
const available: &[Available] = &[
Available { name: String::from("equals"), cons: Box::new(move |a| filters::Equals::from_args(a)) }
];
```
with `available` being an array of available modules, each having a name and a constructor.
However, I rather fail to see the reason for:
* `Box`: In my case, it will be set forever, and be unmutable; and fn is a pointer anyway, so fixed-size…
* `&[…]` notation: In this case, `available` is a constant, and I suppose its size is known at compile-time, so there shouldnt be the need for a reference.
## problem
The above code gives me these errors (which I suspect are hiding the next error about `"equals"` probably being `&str` instead of `String`…):
The above code gives me these errors:
* first:
```
error[E0423]: expected value, found struct `Box`
--> src/modules.rs:10:37
|
10 | Available { name: "equals", cons: Box.new(filters::Equals::from_args) }
| ^^^ constructor is not visible here due to private fields
error[E0277]: the size for values of type `dyn modules::Module` cannot be known at compilation time
--> src/modules.rs:10:69
|
10 | Available { name: String::from("equals"), cons: Box::new(move |a| filters::Equals::from_args(a)) }
| ^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn modules::Module`
```
* second:
```
error[E0277]: the size for values of type `[modules::Available]` cannot be known at compilation time
--> src/modules.rs:9:18
error[E0308]: mismatched types
--> src/modules.rs:10:69
|
9 | const available: [Available] = [
| ^^^^^^^^^^^ doesn't have a size known at compile-time
10 | Available { name: String::from("equals"), cons: Box::new(move |a| filters::Equals::from_args(a)) }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected trait modules::Module, found struct `filters::Equals`
|
= help: the trait `std::marker::Sized` is not implemented for `[modules::Available]`
= note: expected type `dyn modules::Module`
found type `filters::Equals`
```