How to iterate over a collection of structs as an iterator of trait object references? - iterator

I have a collection of struct objects. I'd like to iterate over the collection with an iterator of trait objects, but I can't create an appropriate iterator for that. My reduced test code is:
struct MyStruct {}
struct MyStorage(Vec<MyStruct>);
trait MyTrait {} // Dummy trait to demonstrate the problem
impl MyTrait for MyStruct {}
trait MyContainer {
fn items<'a>(&'a self) -> Box<Iterator<Item = &'a MyTrait> + 'a>;
}
impl MyContainer for MyStorage {
fn items<'a>(&'a self) -> Box<Iterator<Item = &'a MyTrait> + 'a> {
Box::new(self.0.iter())
}
}
This results the following compiler error:
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, MyStruct> as std::iter::Iterator>::Item == &MyTrait`
--> src/main.rs:12:9
|
12 | Box::new(self.0.iter())
| ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `MyStruct`, found trait MyTrait
|
= note: expected type `&MyStruct`
found type `&MyTrait`
= note: required for the cast to the object type `std::iter::Iterator<Item=&MyTrait>`
My understanding is that though &MyStruct is normally convertible to &MyTrait, the Iterator implementation of the standard library doesn't allow it in this case.
Note that the same construct works with a Vec<Box<MyStruct>> and Iterator<Item=&Box<MyTrait>>, but boxing doesn't feel necessary here.
Is there any way to make this work with references?

You need to cast the single elements explicitly, like this:
Box::new(self.0.iter().map(|e| e as &MyTrait))

Related

Why do I get "the method exists but the following trait bounds were not satisfied" when extending Result for failure types?

I'm trying to add a more concise version of the failure crate's .with_context(|e| format!("foo: {}", e)) to my code. Like this playground:
use failure::{Context, Fail, ResultExt}; // 0.1.5
/// Extension methods for failure `Result`.
pub trait ResultContext<T, E> {
/// Wraps the error type in a context type generated by looking at the
/// error value. This is very similar to `with_context` but much more
/// concise.
fn ctx(self, s: &str) -> Result<T, Context<String>>;
}
impl<T, E> ResultContext<T, E> for Result<T, E>
where
E: Fail,
{
fn ctx(self, s: &str) -> Result<T, Context<String>> {
self.map_err(|failure| {
let context = format!("{}: {}", s, failure);
failure.context(context)
})
}
}
pub fn foo() -> Result<i32, failure::Error> {
Ok(5i32)
}
pub fn main() -> Result<(), failure::Error> {
// This works.
let _ = foo().with_context(|_| "foo".to_string())?;
// This doesn't.
foo().ctx("foo")?
}
I get the following error:
error[E0599]: no method named `ctx` found for type `std::result::Result<i32, failure::error::Error>` in the current scope
--> src/main.rs:31:11
|
31 | foo().ctx("foo")?
| ^^^
|
= note: the method `ctx` exists but the following trait bounds were not satisfied:
`std::result::Result<i32, failure::error::Error> : ResultContext<_, _>`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `ctx`, perhaps you need to implement it:
candidate #1: `ResultContext`
I can't work out why. I more or less copied the existing with_context code.
As the compiler tells you, Result<i32, failure::error::Error> doesn't implement ResultContext<_, _>. You have added a bound to your implementation:
where
E: Fail,
But failure::Error doesn't implement failure::Fail:
use failure; // 0.1.5
fn is_fail<F: failure::Fail>() {}
pub fn main() {
is_fail::<failure::Error>();
}
error[E0277]: the trait bound `failure::error::Error: std::error::Error` is not satisfied
--> src/main.rs:6:5
|
6 | is_fail::<failure::Error>();
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::error::Error` is not implemented for `failure::error::Error`
|
= note: required because of the requirements on the impl of `failure::Fail` for `failure::error::Error`
note: required by `is_fail`
--> src/main.rs:3:1
|
3 | fn is_fail<F: failure::Fail>() {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You will need to alter your bounds or your type.

How do I use the Option::ok_or() method correctly?

I'm trying to understand how to use the question mark operator for error handling in Rust. I have this code:
fn main() -> Result<(), &'static str> {
let foo: i32 = Some("1")
.ok_or(Err("error 1"))?
.parse()
.or(Err("error 2"))?;
Ok(())
}
This code can not be compiled for some reason:
error[E0277]: the trait bound `&str: std::convert::From<std::result::Result<_, &str>>` is not satisfied
--> src/main.rs:2:20
|
2 | let foo: i32 = Some("1")
| ____________________^
3 | | .ok_or(Err("error 1"))?
| |_______________________________^ the trait `std::convert::From<std::result::Result<_, &str>>` is not implemented for `&str`
|
= note: required by `std::convert::From::from`
The Rust book has an example usage of the question mark operator:
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
In my opinion, it doesn't differ much from my example in sense of handling errors. I cannot see a reason for my code to be invalid. If the From trait should be implemented for all kinds of Result why does the code from the Rust book work fine?
Unlike or, ok_or takes an E, not a full Result<T, E> (because it wouldn't have anything to do if passed an Ok). Just pass the error string directly:
fn main() -> Result<(), &'static str> {
let foo: i32 = Some("1")
.ok_or("error 1")?
.parse()
.or(Err("error 2"))?;
Ok(())
}
The reason the error message mentions the From trait is because ? implicitly uses From to convert the expression's error type into the return value's error type. If it worked, .ok_or(Err("error 1")) would return a value of Result<&'static str, Result<_, &'static str>> (_ could be almost anything, since Err doesn't specify). The ? operator attempts to find an implementation of From that would convert Result<_, &'static str> (the expression's error type) into &'static str (the return value's error type). Since no such From implementation exists, the compiler emits an error.

How can I box the contents of an iterator of a type that implements a trait?

I'm taking an iterator of some type that must implement the trait A, and trying to convert it into a Vec of Boxes of that trait:
trait A {}
fn test2<'a, I>(iterator: I) -> Vec<Box<A + 'a>>
where
I: IntoIterator,
I::Item: A + 'a,
{
iterator
.into_iter()
.map(|a| Box::new(a))
.collect::<Vec<Box<A + 'a>>>()
}
However, this fails to compile, saying:
error[E0277]: the trait bound `std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not satisfied
--> src/main.rs:11:10
|
11 | .collect::<Vec<Box<A + 'a>>>()
| ^^^^^^^ a collection of type `std::vec::Vec<std::boxed::Box<A + 'a>>` cannot be built from an iterator over elements of type `std::boxed::Box<<I as std::iter::IntoIterator>::Item>`
|
= help: the trait `std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not implemented for `std::vec::Vec<std::boxed::Box<A + 'a>>`
= help: consider adding a `where std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` bound
This error kind of makes sense, but then I don't see why there's no problem with the following:
fn test<'a, T: A + 'a>(t: T) -> Box<A + 'a> {
Box::new(t)
}
How is that any different? How can I express that I'd like to Box them as As, rather than whatever type they may be?
You need to cast the Box<I::Item> into a Box<A>:
fn test2<'a, I>(iterator: I) -> Vec<Box<dyn A + 'a>>
where
I: IntoIterator,
I::Item: A + 'a,
{
iterator
.into_iter()
.map(|a| Box::new(a) as Box<dyn A>)
.collect()
}
How is [returning Box::new directly] any different?
As Sven Marnach points out:
The reason why you don't need an explicit cast in the function is that the last statement of a block is a coercion site and coercions happen implicitly at these sites. See the chapter on coercions in the nomicon for further details.

Convert vector of enum values into an another vector

I have the following code which generates a vector of bytes from the passed vector of enum values:
#[derive(Debug, PartialEq)]
pub enum BertType {
SmallInteger(u8),
Integer(i32),
Float(f64),
String(String),
Boolean(bool),
Tuple(BertTuple),
}
#[derive(Debug, PartialEq)]
pub struct BertTuple {
pub values: Vec<BertType>
}
pub struct Serializer;
pub trait Serialize<T> {
fn to_bert(&self, data: T) -> Vec<u8>;
}
impl Serializer {
fn enum_value_to_binary(&self, enum_value: BertType) -> Vec<u8> {
match enum_value {
BertType::SmallInteger(value_u8) => self.to_bert(value_u8),
BertType::Integer(value_i32) => self.to_bert(value_i32),
BertType::Float(value_f64) => self.to_bert(value_f64),
BertType::String(string) => self.to_bert(string),
BertType::Boolean(boolean) => self.to_bert(boolean),
BertType::Tuple(tuple) => self.to_bert(tuple),
}
}
}
// some functions for serialize bool/integer/etc. into Vec<u8>
// ...
impl Serialize<BertTuple> for Serializer {
fn to_bert(&self, data: BertTuple) -> Vec<u8> {
let mut binary: Vec<u8> = data.values
.iter()
.map(|&item| self.enum_value_to_binary(item)) // <-- what the issue there?
.collect();
let arity = data.values.len();
match arity {
0...255 => self.get_small_tuple(arity as u8, binary),
_ => self.get_large_tuple(arity as i32, binary),
}
}
}
But when compiling, I receive an error with iterating around map:
error: the trait bound `std::vec::Vec<u8>: std::iter::FromIterator<std::vec::Vec<u8>>` is not satisfied [E0277]
.collect();
^~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
note: a collection of type `std::vec::Vec<u8>` cannot be built from an iterator over elements of type `std::vec::Vec<u8>`
error: aborting due to previous error
error: Could not compile `bert-rs`.
How can I fix this issue with std::iter::FromIterator?
The problem is that enum_value_to_binary returns a Vec<u8> for each element in values. So you end up with an Iterator<Item=Vec<u8>> and you call collect::<Vec<u8>>() on that, but it doesn't know how to flatten the nested vectors. If you want all the values to be flattened into one Vec<u8>, then you should use flat_map instead of map:
let mut binary: Vec<u8> = data.values
.iter()
.flat_map(|item| self.enum_value_to_binary(item).into_iter())
.collect();
Or, slightly more idiomatic and performant, you can just have enum_value_to_binary return an iterator directly.
Also, the iter method returns an Iterator<Item=&'a T>, which means you are just borrowing the elements, but self.enum_value_to_binary wants to take ownership over the value. There's a couple of ways to fix that. One option would be to use into_iter instead of iter, which will give you the elements by value. If you do that, you'll move the arity variable up to before the binary variable, since creating the binary variable will take ownership (move) data.values.
The other option would be to change self.enum_value_to_binary to take it's argument by reference.
Also possible that you meant for the type of binary to actually be Vec<Vec<u8>>.

Implementing a "cautious" take_while using Peekable

I'd like to use Peekable as the basis for a new cautious_take_while operation that acts like take_while from IteratorExt but without consuming the first failed item. (There's a side question of whether this is a good idea, and whether there are better ways to accomplish this goal in Rust -- I'd be happy for hints in that direction, but mostly I'm trying to understand where my code is breaking).
The API I'm trying to enable is basically:
let mut chars = "abcdefg.".chars().peekable();
let abc : String = chars.by_ref().cautious_take_while(|&x| x != 'd');
let defg : String = chars.by_ref().cautious_take_while(|&x| x != '.');
// yielding (abc = "abc", defg = "defg")
I've taken a crack at creating a MCVE here, but I'm getting:
:10:5: 10:19 error: cannot move out of borrowed content
:10 chars.by_ref().cautious_take_while(|&x| x != '.');
As far as I can tell, I'm following the same pattern as Rust's own TakeWhile in terms of my function signatures, but I'm seeing different different behavior from the borrow checker. Can someone point out what I'm doing wrong?
The funny thing with by_ref() is that it returns a mutable reference to itself:
pub trait IteratorExt: Iterator + Sized {
fn by_ref(&mut self) -> &mut Self { self }
}
It works because the Iterator trait is implemented for the mutable pointer to Iterator type. Smart!
impl<'a, I> Iterator for &'a mut I where I: Iterator, I: ?Sized { ... }
The standard take_while function works because it uses the trait Iterator, that is automatically resolved to &mut Peekable<T>.
But your code does not work because Peekable is a struct, not a trait, so your CautiousTakeWhileable must specify the type, and you are trying to take ownership of it, but you cannot, because you have a mutable pointer.
Solution, do not take a Peekable<T> but &mut Peekable<T>. You will need to specify the lifetime too:
impl <'a, T: Iterator, P> Iterator for CautiousTakeWhile<&'a mut Peekable<T>, P>
where P: FnMut(&T::Item) -> bool {
//...
}
impl <'a, T: Iterator> CautiousTakeWhileable for &'a mut Peekable<T> {
fn cautious_take_while<P>(self, f: P) -> CautiousTakeWhile<&'a mut Peekable<T>, P>
where P: FnMut(&T::Item) -> bool {
CautiousTakeWhile{inner: self, condition: f,}
}
}
A curious side effect of this solution is that now by_ref is not needed, because cautious_take_while() takes a mutable reference, so it does not steal ownership. The by_ref() call is needed for take_while() because it can take either Peekable<T> or &mut Peekable<T>, and it defaults to the first one. With the by_ref() call it will resolve to the second one.
And now that I finally understand it, I think it might be a good idea to change the definition of struct CautiousTakeWhile to include the peekable bit into the struct itself. The difficulty is that the lifetime has to be specified manually, if I'm right. Something like:
struct CautiousTakeWhile<'a, T: Iterator + 'a, P>
where T::Item : 'a {
inner: &'a mut Peekable<T>,
condition: P,
}
trait CautiousTakeWhileable<'a, T>: Iterator {
fn cautious_take_while<P>(self, P) -> CautiousTakeWhile<'a, T, P> where
P: FnMut(&Self::Item) -> bool;
}
and the rest is more or less straightforward.
This was a tricky one! I'll lead with the meat of the code, then attempt to explain it (if I understand it...). It's also the ugly, unsugared version, as I wanted to reduce incidental complexity.
use std::iter::Peekable;
fn main() {
let mut chars = "abcdefg.".chars().peekable();
let abc: String = CautiousTakeWhile{inner: chars.by_ref(), condition: |&x| x != 'd'}.collect();
let defg: String = CautiousTakeWhile{inner: chars.by_ref(), condition: |&x| x != '.'}.collect();
println!("{}, {}", abc, defg);
}
struct CautiousTakeWhile<'a, I, P> //'
where I::Item: 'a, //'
I: Iterator + 'a, //'
P: FnMut(&I::Item) -> bool,
{
inner: &'a mut Peekable<I>, //'
condition: P,
}
impl<'a, I, P> Iterator for CautiousTakeWhile<'a, I, P>
where I::Item: 'a, //'
I: Iterator + 'a, //'
P: FnMut(&I::Item) -> bool
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
let return_next =
match self.inner.peek() {
Some(ref v) => (self.condition)(v),
_ => false,
};
if return_next { self.inner.next() } else { None }
}
}
Actually, Rodrigo seems to have a good explanation, so I'll defer to that, unless you'd like me to explain something specific.