gpt4 book ai didi

rust - 为什么 T 不实现 AsRef

转载 作者:行者123 更新时间:2023-11-29 07:52:23 24 4
gpt4 key购买 nike

此代码无法编译:

fn ref_on_int<T>(_: T) where T: AsRef<i32> {}

fn main() {
ref_on_int(&0_i32)
}

因为

the trait bound `i32: std::convert::AsRef<i32>` is not satisfied

为什么会这样?

这对于像这样的新类型可能很有用

struct MyInt(i32);

impl AsRef<i32> for MyInt {
/* etc. */
}

然后您可以无差别地传递对 i32 的引用或对 MyInt 的引用,因为在这两种情况下我们在内存中都有一个 i32.

最佳答案

AsRefBorrow 乍一看非常相似,但它们用于不同的事情。 The Book很好地描述了它们之间的区别:

Choose Borrow when you want to abstract over different kinds of borrowing, or when you’re building a data structure that treats owned and borrowed values in equivalent ways, such as hashing and comparison.

Choose AsRef when you want to convert something to a reference directly, and you’re writing generic code.

在您的情况下,Borrow 是更合理的选择,因为不涉及任何转换。

至于为什么 AsRef 没有在不同的整数类型之间实现的问题,我想这违背了 Rust 表达强制转换的意图;我认为这类似于问题 Why can't I compare two integers of different types? .

关于rust - 为什么 T 不实现 AsRef<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48887413/

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