简体   繁体   English

为什么我们不需要在某些rust迭代器中从Result提取值?

[英]Why don't we need to extract values from Result in some rust iterators?

Here, I have a simple map and sum over an iterator: 在这里,我有一个简单的映射并通过迭代器求和:

fn main() {
    let s = "
aoeu
aoeu
aoeu
aoeu
";

    let ls = s.lines();
    let i: usize = ls.map(|l| l.len()).sum();
    dbg!(i);
}

This compiles and runs fine. 这样可以编译并正常运行。 When I look at the source for lines , the next method returns Option<Result<String>> . 当我查看lines源代码时next方法将返回Option<Result<String>>

But the map above calls .len() directly on each item. 但是上面的地图直接在每个项目上调用.len() I understand the value is extracted from inside the Option (a None value would mean the end of the iterator). 我知道该值是从Option内部提取的( None值表示迭代器的结尾)。 Is .len() being called on the Result object? 是否在Result对象上调用.len() Why don't we need to call something like map() * to extract the value from Result ? 为什么我们不需要调用诸如map() *之类的东西来从Result提取值?

Thanks! 谢谢!

* I had thought Result::map had a different meaning to Iterator::map , but maybe I'm confusing myself... *我以为Result::mapIterator::map含义有所不同,但也许让我感到困惑...

There are two lines in the standard library. 标准库中有两lines

The one on str , which returns std::str::Lines , which is an iterator of &str . str一个 ,返回std::str::Lines ,它是&str的迭代器。 This is the one you are using. 这是您正在使用的那个。 Splitting a string cannot fail, so it doesn't need to use Result . 分割字符串不会失败,因此不需要使用Result

And the one on std::io::BufRead , which returns std::io::Lines . 还有一个在std::io::BufRead ,它返回std::io::Lines This one reads from a BufRead , which can fail (eg. reading a file on a network drive can fail if the drive becomes unreachable), so it must return a Result . 这是从BufRead读取的,这可能会失败(例如,如果驱动器变得无法访问,则读取网络驱动器上的文件可能会失败),因此它必须返回Result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么Option的Some和None变体不需要合格? - Why don't Option's Some and None variants need to be qualified? 如果我们有不可变变量,为什么我们需要 Rust 中的常量? - Why do we need constants in Rust if we have immutable variables? 为什么我们需要在 Rust 中指定所有依赖(包括传递)? - Why we need to specify all dependencies (including transitives) in Rust? 为什么相同签名的 Rust 闭包不具有相同的类型? - Why don't Rust closures of the same signature have the same type? 为什么Rust不使用默认通用参数类型 - Why Rust don't use default generic parameter type 有没有更简洁的方法从 Rust 中的选项中提取值 - Is there a less verbose way to extract values from Options in Rust 为什么我们不从Iterator实现所有函数来实现迭代器? - Why don't we implement all the functions from Iterator to implement an iterator? 为什么从 C 调用 Rust 库会导致 memory 泄漏? - Why does calling a Rust library from C result in memory leakage? 当我不关心某些 arguments 时,Rust 可以在 function 类型之间转换吗? - Can Rust cast between function types when I don't care about some of the arguments? 为什么我们需要使用 function 名称来定义泛型类型而不是 Rust 中的参数签名? - Why do we need to define the generic type with the function name other than the parameter signatures in Rust?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM