G'day Stackoverflowers,
我是Perl的autodie pragma 的作者,它改变了Perl的内置函数,以便在失败时抛出异常.它类似于Fatal,但具有词法范围,可扩展的异常模型,更智能的返回检查以及更多更好的错误消息.它将Fatal在未来的Perl版本(暂定5.10.1+)中替换该模块,但目前可以从CPAN for Perl 5.8.0及更高版本下载.
下一个版本autodie将为flock使用LOCK_NB(非阻塞)选项的调用添加特殊处理.虽然失败的flock调用通常会导致异常autodie,但是如果返回的errno()是,则对flock使用失败的调用LOCK_NB将仅返回false .$!EWOULDBLOCK
这样做的原因是人们可以继续编写如下代码:
use Fcntl qw(:flock);
use autodie; # All perl built-ins now succeed or die.
open(my $fh, '<', 'some_file.txt');
my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can.
if ($lock) {
# Opportuntistically do something with the locked file.
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,由于其他人已将文件锁定为has(EWOULDBLOCK)而失败的锁定不被视为硬错误,因此自动重放 …
autodie文档提示可以将它用于除默认情况下可以处理的内置函数之外的其他函数,但是没有明确的示例如何在其中执行此操作.
具体来说,我想将它用于Imager模块.许多功能和方法可能会失败,我更愿意,如果这并不意味着我的代码将遍布各种or die Imager|$image->errstr;短语.
当然,如果有另一种方式而不是使用autodie来实现这一点,我也会对此感兴趣.
我有以下函数,它应该找到并返回String给定的最长长度Iterator:
fn max_width(strings: &Iterator<Item = &String>) -> usize {
let mut max_width = 0;
for string in strings {
if string.len() > max_width {
max_width = string.len();
}
}
return max_width;
}
Run Code Online (Sandbox Code Playgroud)
但是,编译器给出了以下错误:
error[E0277]: the trait bound `&std::iter::Iterator<Item=&std::string::String>: std::iter::Iterator` is not satisfied
--> src/main.rs:3:19
|
3 | for string in strings {
| ^^^^^^^ `&std::iter::Iterator<Item=&std::string::String>` is not an iterator; maybe try calling `.iter()` or a similar method
|
= help: the trait `std::iter::Iterator` is not implemented …Run Code Online (Sandbox Code Playgroud)