Skip to content
GitLab
Menu
Why GitLab
Pricing
Contact Sales
Explore
Why GitLab
Pricing
Contact Sales
Explore
Sign in
Get free trial
Changes
Page history
Update rust error
authored
Nov 15, 2021
by
umaumax
Show whitespace changes
Inline
Side-by-side
rust/rust-error.md
View page @
e24d78ef
...
@@ -226,3 +226,44 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
...
@@ -226,3 +226,44 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
参照は残っているように見え、参照するライフタイムの影響が残る
参照は残っているように見え、参照するライフタイムの影響が残る
`.map_err(|e| anyhow::anyhow!(e.to_string()))?;`
とすることで、ライフタイムを参照しないエラーを返すことができる
`.map_err(|e| anyhow::anyhow!(e.to_string()))?;`
とすることで、ライフタイムを参照しないエラーを返すことができる
## &Resultの扱い方
例えば、イテレータの各要素にResultを詰めて、
`.peekable()`
を読んでから、
`.peek()`
すると
`&Result`
が発生する
```
rust
fn
main
()
->
Result
<
(),
std
::
io
::
Error
>
{
let
result
:
Result
<
String
,
std
::
io
::
Error
>
=
Ok
(
"ok"
.to_string
());
let
ref_result
=
&
result
;
// .as_ref()は&Result<T, E>をResult<&T, &V>へ変換する
// unwrap()ならば問題とならないが、
// the trait `From<&std::io::Error>` is not implemented for `std::io::Error`
// となるので、?がそのまま利用できない
// let x = ref_result.as_ref()?;
let
x
=
ref_result
.as_ref
()
.unwrap
();
Ok
(())
}
fn
main
()
->
Result
<
(),
std
::
io
::
Error
>
{
let
mut
iter
=
vec!
[
Ok
(
1
as
i32
),
Ok
(
2
as
i32
),
Err
(
std
::
io
::
Error
::
new
(
std
::
io
::
ErrorKind
::
Other
,
"oh no!"
)),
]
.into_iter
()
.peekable
();
loop
{
if
let
Some
(
v
)
=
iter
.peek
()
{
// Result型はCopy traitを実装していないので、moveが発生してしまうことが問題となっている
// 参照のままでは所有権の問題があるので、要素のエラーを帰す場合にはおとなしく.next()を利用する必要がある
let
r
:
&
Result
<
i32
,
std
::
io
::
Error
>
=
v
;
if
r
.as_ref
()
.is_ok
()
{
println!
(
"{}"
,
r
.as_ref
()
.unwrap
());
}
iter
.next
()
.unwrap
()
?
;
}
else
{
break
;
};
}
Ok
(())
}
```
\ No newline at end of file