gpt4 book ai didi

generics - 生命周期结束时,通用类型参数不受限制

转载 作者:行者123 更新时间:2023-12-03 11:38:04 26 4
gpt4 key购买 nike

为什么以下内容无法编译?

trait A<'a> {
type Typ;
}

trait B {}

struct C<T> {
_ph: std::marker::PhantomData<T>,
}

impl<'a, T, V> B for C<T> where
T: A<'a, Typ=V>
{}
playground
前面给出了错误“类型参数 V不受impl特性,自身类型或谓词的约束”。将关联类型更改为通用类型也不会编译,从而产生相同的错误。
但是,如果删除生命周期,则会编译以下内容。
trait A {
type Typ;
}

trait B {}

struct C<T> {
_ph: std::marker::PhantomData<T>,
}

impl<T, V> B for C<T> where
T: A<Typ=V>
{}
playground
删除关联的类型也会进行编译。
trait A<'a> {}

trait B {}

struct C<T> {
_ph: std::marker::PhantomData<T>,
}

impl<'a, T> B for C<T> where
T: A<'a>
{}
playground
看到仅仅删除生命周期是如何导致代码编译的(不以任何方式更改V),我猜测错误消息不是真正的潜在错误。我不知道不进行编译的真正原因是什么。
最初出现的情况并不真正相关-这个问题更多关于奇怪的行为和错误消息,但是如果需要,可以查看 here

最佳答案

它提示是因为您没有限制该泛型。
就像写:

impl<A> SomeTrait for MyType {}
// We aren't using A
这将很好用,因为它已经对 Typ是通用的:
impl<'a, T> B for C<T> where
T: A<'a>,
{
// you can refer to your V type as <T as A>::Typ
}
如果确实要限制它,则可以:
use std::default::Default;

impl<'a, T> B for C<T> where
T: A<'a>,
<T as A<'a>>::Typ: Default,
{
// now here you can call <T as A<'a>>::Typ::default()
}

关于generics - 生命周期结束时,通用类型参数不受限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66309200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com