如何强制特征的两个关联类型参数相等? [英] How can I enforce equality of two associated type parameters of traits?

查看:58
本文介绍了如何强制特征的两个关联类型参数相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数f,它接受两个相同类型的参数,一个函数g,它接受两个不同类型的参数,但是两种类型都必须存储相同的值,以便g可以调用f,其值包含在f的参数中.我目前实现了这样的内容:

I have a function f which takes two arguments of the same type, and a function g which takes two arguments of different types, but both types have to store the same value, so that g can call f with the values contained in the arguments to f. I currently implemented something like this:

fn f<T>(a: T, b: T) {}

trait A {
    type A;
    fn getter(&self) -> Self::A;
}

fn g<T: A, U: A>(a: T, b: U) {
    f(a.getter(), b.getter())
}

要使g的定义生效,我必须添加什么?

What do I have to add to the definition of g to make it work?

推荐答案

一个where子句可以正常工作:

A where clause works fine:

fn g<T, U>(a: T, b: U)
where
    T: A,
    U: A<A = T::A>, // where T::A is equal to B::A
{
    f(a.getter(), b.getter())
}

这篇关于如何强制特征的两个关联类型参数相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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