基于枚举输入返回不同类型的泛型函数 [英] Generic function that return different types based on an enum input

查看:67
本文介绍了基于枚举输入返回不同类型的泛型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存寄存器的结构.我希望我的read_register函数为Register::V0Register::V1返回u8但为Register::V2Register::V3返回u16.我不确定如何使函数在输入类型上通用.我收到错误match arms have incompatible types,它的确有意义,因为类型不同.

I have a struct which holds registers. I want my read_register function to return a u8 for Register::V0 and Register::V1 but a u16 for Register::V2 and Register::V3. I'm not sure how to make the function generic for over the input type. I'm getting the error match arms have incompatible types which does make sense because the types are different.

struct Registers {
    v0: u8,
    v1: u8,
    v2: u16,
    v3: u16,
}

enum Register {
    V0,
    V1,
    V2,
    V3,
}

impl Registers {
    fn read_register<T>(&self, register: Register) -> T {
        match register {
            Register::V0 => self.v0,
            Register::V1 => self.v1,
            Register::V2 => self.v2,
            Register::V3 => self.v3,
        }
    }
}

推荐答案

您不能.

对不起,但是Rust没办法做到这一点.您将需要Rust没有的依赖类型.您也许可以返回enum的实例,该实例仅包含两个变体(每种类型一个).或者,您可以为每个路径"接受一个回调,然后让调用者决定如何解决问题.

Sorry, but there's just no way of doing this in Rust. You'd need dependent types, which Rust doesn't have. You could perhaps return an instance of an enum that just contains two variants (one for each type). Or you could accept one callback for each "path" and let the caller decide how to resolve the problem.

fn read_register<FnU8, FnU16, R>(
    &self,
    register: Register,
    with_u8: FnU8,
    with_u16: FnU16,
) -> R
where
    FnU8: FnOnce(u8) -> R,
    FnU16: FnOnce(u16) -> R,
{
    match register {
        Register::V0 => with_u8(self.v0),
        Register::V1 => with_u8(self.v1),
        Register::V2 => with_u16(self.v2),
        Register::V3 => with_u16(self.v3),
    }
}

这篇关于基于枚举输入返回不同类型的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆