Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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