gpt4 book ai didi

rust - 为什么Rust阻止为外部结构实现外部特征?

转载 作者:行者123 更新时间:2023-12-03 11:31:32 25 4
gpt4 key购买 nike

我只是遇到了为我不拥有的类型实现我不拥有的特征的问题。然后我用谷歌搜索了确切的How do I implement a trait I don't own for a type I don't own?问题。
使我感到困惑的是这种限制的动机。我来自Scala,可以在其中为外部类型使用外部typeclass实例。
为什么Rust限制了这一点?

最佳答案

我刚刚阅读了有关实现特征的Rust Book章节,正如@AlexLarionov在评论中建议的那样,选择合适的实现是不可能的:

But we can’t implement external traits on external types. For example,we can’t implement the Display trait on Vec<T> within our aggregatorcrate, because Display and Vec<T> are defined in the standard libraryand aren’t local to our aggregator crate. This restriction is part ofa property of programs called coherence, and more specifically theorphan rule, so named because the parent type is not present. Thisrule ensures that other people’s code can’t break your code and viceversa. Without the rule, two crates could implement the same trait forthe same type, and Rust wouldn’t know which implementation to use.

关于rust - 为什么Rust阻止为外部结构实现外部特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63093321/

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