How do I make a structure generic in Rust without higher kinded type (HKT) support?

让人想犯罪 __ 提交于 2021-02-08 17:38:58

问题


I am trying to make the Iteratee structure generic so I can pass in a different parsing function and get an different Iteratee. This is the non-generic version that works:

use std::io::{BufRead, BufReader};
use std::str::{from_utf8, Utf8Error};

#[derive(PartialEq, Debug)]
struct Cat<'a> {
    name: &'a str,
}

fn parse<'a>(slice: &'a [u8]) -> Result<Cat<'a>, Utf8Error> {
    from_utf8(slice).map(|name| Cat { name: name })
}

struct Iteratee<R>
    where R: BufRead + Sized
{
    read: R,
}

impl<R> Iteratee<R>
    where R: BufRead + Sized
{
    fn next<'a, F>(&'a mut self, fun: F)
        where F: Fn(Option<Result<Cat<'a>, Utf8Error>>) -> () + Sized
    {
        let slice = self.read.fill_buf().unwrap();
        fun(Some(parse(slice)))
        //       ^^^^^^^^^^^ How do I pull 'parse' up as a function of Iteratee
    }
}

fn main() {
    let data = &b"felix"[..];
    let read = BufReader::new(data);
    let mut iterator = Iteratee { read: read };
    iterator.next(|cat| assert_eq!(cat.unwrap().unwrap(), Cat { name: "felix" }));
}

This is my attempt at making it generic, but I can't construct IterateeFun with either a reference to the function or passing in a closure.

struct IterateeFun<R, P, T>
    where R: BufRead + Sized,
          P: Fn(&[u8]) -> (Result<T, Utf8Error>) + Sized
{
    read: R,
    parser: P,
}

impl<R, P, T> IterateeFun<R, P, T>
    where R: BufRead + Sized,
          P: Fn(&[u8]) -> (Result<T, Utf8Error>) + Sized
{
    fn next<'a, F>(&'a mut self, fun: F)
        where F: Fn(Option<Result<T, Utf8Error>>) -> () + Sized
    {
        let slice = self.read.fill_buf().unwrap();
        fun(Some((self.parser)(slice)))
    }
}


fn main() {
    let data = &b"felix"[..];
    let read = BufReader::new(data);
    let mut iterator = IterateeFun {
        read: read,
        parser: parse, // What can I put here?
        // I've tried a closure but then I get error[E0495]/ lifetime issues
    };

    iterator.next(|cat| assert_eq!(cat.unwrap().unwrap(), Cat { name: "felix" }));
}

I'd like to know how to pass a function into a structure as shown. Or should I be doing this as a trait instead?


回答1:


As with most problems I just needed another level of indirection! Higher kinded types (HKT) would obviously help but I actually only need to be able to associate a lifetime parameter with my parsing function.

Inspired by user4815162342 and Streamer I realised I could create two traits Iteratee<'a> and Parser<'a> each with an associated type and then when I create an implementation that combines them I would be able to combine the associated types to give me a form of HKTs:

trait Parser<'a> {
    type Output: 'a;

    fn parse(&self, &'a [u8]) -> Result<Self::Output, Utf8Error>;
}

struct CatParser;

impl<'a> Parser<'a> for CatParser{
    type Output = Cat<'a>;

    fn parse(&self, slice: &'a [u8]) -> Result<Self::Output, Utf8Error> {
        parse(slice)
    }
}

trait Iteratee<'a> {
    type Item: 'a;

    fn next<F>(&'a mut self, fun: F) where F: Fn(Option<Self::Item>) -> () + Sized;
}

struct IterateeParser<R, P> {
    read: R,
    parser: P,
}

impl<'a, R, P> Iteratee<'a> for IterateeParser<R,P> where R: BufRead + Sized, P: Parser<'a> {
    type Item = Result<P::Output, Utf8Error>;
    //                 ^^^^^^^^^ This is the magic!

    fn next<F>(&'a mut self, fun: F) where F: Fn(Option<Self::Item>) -> () + Sized {
        let slice = self.read.fill_buf().unwrap();
        fun(Some(self.parser.parse(slice)))
    }
}

fn main() {
    let data = &b"felix"[..];
    let read = BufReader::new(data);
    let mut iterator = IterateeParser { read: read, parser: CatParser };
    iterator.next(|cat| assert_eq!(cat.unwrap().unwrap(), Cat { name: "felix" }));
}

The magic line is type Item = Result<P::Output, Utf8Error>;



来源:https://stackoverflow.com/questions/41784344/how-do-i-make-a-structure-generic-in-rust-without-higher-kinded-type-hkt-suppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!