gpt4 book ai didi

rust - 如何为不带 self 的特征函数提供类型参数?

转载 作者:行者123 更新时间:2023-11-29 08:04:21 24 4
gpt4 key购买 nike

这不编译:

pub trait TheTrait<T> {
pub fn without_self() -> T;
pub fn with_self(&self) -> T {
TheTrait::without_self()
}
}

因为编译器无法找出 TheTrait::without_self() 的类型参数.我想要类似 TheTrait<T>::without_self() 的东西, 但我找不到有效的语法。如何向 without_self 提供类型参数?

最佳答案

Editor's note: This answer is outdated as of Rust 1.0

如果没有 Selfself在函数签名中,它不可调用,至少直到UFCS。实现。现在,您可以使用 Option<Self>作为参数,并调用 None::<Self>作为解决方法。

pub trait TheTrait<T> {
fn without_self(Option<Self>) -> T;
fn with_self(&self) -> T {
TheTrait::without_self(None::<Self>)
}
}

关于rust - 如何为不带 self 的特征函数提供类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539175/

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