英文:
&T Into bool where T: Into<bool>
问题
I have a function with a generic T
which is Into<bool>
. I can't figure out how to convert a reference, &T
into bool
. My understanding of Into
or generics are wrong because I thought this would work:
// error[E0277]: the trait bound `bool: From<&T>` is not satisfied
fn ref_bool<T: Into<bool>>(input: &T) -> bool {
input.into()
// ^^^^ the trait `From<&T>` is not implemented for `bool`
}
How can I fix this so that I can convert &T
into a bool
?
英文:
I have a function with a generic T
which is Into<bool>
. I can't figure out how to convert a reference, &T
into bool
. My understanding of Into
or generics are wrong because I thought this would work:
// error[E0277]: the trait bound `bool: From<&T>` is not satisfied
fn ref_bool<T: Into<bool>>(input: &T) -> bool {
input.into()
// ^^^^ the trait `From<&T>` is not implemented for `bool`
}
How can I fix this so that I can convert &T
into a bool
?
答案1
得分: 3
你可以通过在&T
上加上特质限定来使这个方法编译通过。
fn ref_bool<'a, T>(input: &'a T) -> bool where &'a T: Into<bool> {
input.into()
}
显式生命周期仅在 where 子句中生命周期无法推断时才必要。
然而,这个函数没有太多意义。你传递给它的任何值也可以传递给这个更简单的函数:
fn into_bool<T: Into<bool>>(input: T) -> bool {
input.into()
}
在这种情况下,它与Into::into
相同,因此你可以直接使用Into::into
。
其他解决方案可能不会达到你的预期。Into
特质用于消耗输入的转换,因此它通常不会为引用实现。通常,不消耗输入并返回bool
的操作是特定于类型的,例如Vec::is_empty
或Option::is_none
。标准库中没有像你在其他语言中可能找到的真值特质,特别是在动态类型语言中。在 Rust 中,通常会尽早将某些东西转换为bool
,然后再将其传递给函数,从而避免了真值特质的需求。
英文:
You can make this method compile by putting the trait bound on &T
.
fn ref_bool<'a, T>(input: &'a T) -> bool where &'a T: Into<bool> {
input.into()
}
The explicit lifetime is only necessary because lifetimes in where clauses aren't inferred.
However, this function makes little sense. Any value you pass into it can also be passed into this simpler function:
fn into_bool<T: Into<bool>>(input: T) -> bool {
input.into()
}
And in that case, it's the same as Into::into
, so you might as well use Into::into
directly.
These other solutions might not do what you intend. The Into
trait is meant for conversions that consume the input, so it's not often implemented for references. Usually non-consuming operations that return a bool
are specific to the type, like Vec::is_empty
or Option::is_none
. There isn't a trait in the standard library for truthiness like you may find in other languages, particularly dynamically typed languages. In rust, you'd typically convert something to a bool
as soon as possible, before passing it into a function, which avoids the need for a truthiness trait.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论