Created
October 30, 2019 18:14
-
-
Save KeenS/3def338ad482182bc5030b82216aa687 to your computer and use it in GitHub Desktop.
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
use std::ops::{Index, IndexMut}; | |
pub struct User { | |
id: u64, | |
name: String, | |
} | |
impl User { | |
pub fn new(id_var: u64, name_var: String) -> Self { | |
User { | |
id: id_var, | |
name: name_var, | |
} | |
} | |
} | |
// Userへのインデクシング専用の型を定義する | |
#[allow(non_camel_case_types)] | |
pub struct id; | |
#[allow(non_camel_case_types)] | |
struct name; | |
// それぞれのインデックスとフィールドを対応づけてIndexとIndexMutを実装する | |
impl Index<id> for User { | |
type Output = u64; | |
fn index(&self, _: id) -> &Self::Output { | |
&self.id | |
} | |
} | |
impl IndexMut<id> for User { | |
fn index_mut(&mut self, _: id) -> &mut Self::Output { | |
&mut self.id | |
} | |
} | |
impl Index<name> for User { | |
type Output = String; | |
fn index(&self, _: name) -> &Self::Output { | |
&self.name | |
} | |
} | |
impl IndexMut<name> for User { | |
fn index_mut(&mut self, _: name) -> &mut Self::Output { | |
&mut self.name | |
} | |
} | |
fn main() { | |
let mut user = User::new(1, "user".into()); | |
assert_eq!(user[name], "user"); | |
user[id] += 1; | |
assert_eq!(user[id], 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment