Skip to content

Instantly share code, notes, and snippets.

@KeenS
Created October 30, 2019 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KeenS/3def338ad482182bc5030b82216aa687 to your computer and use it in GitHub Desktop.
Save KeenS/3def338ad482182bc5030b82216aa687 to your computer and use it in GitHub Desktop.
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