Skip to content

Instantly share code, notes, and snippets.

@Cypher1
Created October 31, 2022 05:17
Show Gist options
  • Save Cypher1/9e643fa09496f37e4f80831132ac509c to your computer and use it in GitHub Desktop.
Save Cypher1/9e643fa09496f37e4f80831132ac509c to your computer and use it in GitHub Desktop.
Ideas about the rust type system
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
trait ToRef<T> {
fn to_ref(&self) -> &T;
}
trait ToRefMut<T>: ToRef<T> {
fn to_mut(&mut self) -> &mut T;
}
impl<T> ToRef<T> for T {
fn to_ref(&self) -> &T {
self
}
}
impl<T> ToRefMut<T> for T {
fn to_mut(&mut self) -> &mut T {
self
}
}
impl<T> ToRef<T> for &mut T {
fn to_ref(&self) -> &T {
self
}
}
impl<T> ToRefMut<T> for &mut T {
fn to_mut(&mut self) -> &mut T {
self
}
}
impl<T> ToRef<T> for &T {
fn to_ref(self: &Self) -> &T {
self
}
}
fn f(a: impl ToRef<u32>) {
let a = a.to_ref();
dbg!(a);
}
fn g(mut a: impl ToRefMut<u32>) {
let a = a.to_mut();
*a += 1;
dbg!(a);
}
fn main() {
let mut a = 3;
f(&a);
g(&mut a);
g(a); // This gets a copy
f(a); // This gets the old `a`.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment