Last active
August 6, 2020 07:39
-
-
Save totem3/1088fab65968a66c1723019b4e2bf629 to your computer and use it in GitHub Desktop.
mapにするとうまくいかないやつがわかったとき
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Nanika { | |
v: V, | |
} | |
struct V(u8); | |
impl V { | |
fn incr(&mut self) { | |
self.0 += 1 | |
} | |
} | |
impl Nanika { | |
fn do_nanika(&mut self) -> Option<&V> { | |
self.v.incr(); | |
Some(&V(1)) | |
} | |
fn get_nanika(&self) -> Option<&V> { | |
Some(&self.v) | |
} | |
} | |
fn main() { | |
let mut n = Nanika { v: V(0) }; | |
let v = n.v.0; | |
// これはOKだけどNoneのケースが冗長なので書きたくない | |
let _ = match n.do_nanika() { | |
Some(nanika) => Some(nanika.0 * n.v.0), | |
None => None | |
}; | |
let _ = n.do_nanika().map(|nanika| { | |
// nanika.0 * n.v.0 | |
// ^ これはエラー。 | |
nanika.0 * v | |
}); | |
// これは不変なのでOK | |
let _ = n.get_nanika().map(|nanika| { | |
nanika.0 * n.v.0 | |
}); | |
} |
Author
totem3
commented
Aug 6, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment