Skip to content

Commit

Permalink
Move trait examples to separate .rs files
Browse files Browse the repository at this point in the history
  • Loading branch information
john-cd committed Dec 29, 2023
1 parent 159c147 commit 77059fc
Show file tree
Hide file tree
Showing 13 changed files with 238 additions and 203 deletions.
15 changes: 15 additions & 0 deletions deps/examples/associated_types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
trait Iterator {
type Item; // <-- associated type
// in Impl, use e.g. `Iterator<Item = u32>`

fn next(&mut self) -> Option<Self::Item>;
}

// Generic type with default
trait Add<Rhs = Self> {
type Output; // <-- associated type

fn add(self, rhs: Rhs) -> Self::Output;
}

fn main() {}
13 changes: 13 additions & 0 deletions deps/examples/const_in_traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
trait Example {
const CONST_NO_DEFAULT: i32;
const CONST_WITH_DEFAULT: i32 = 99;
}
struct S;

impl Example for S {
const CONST_NO_DEFAULT: i32 = 0;
}

fn main() {
println!("{} {}", S::CONST_NO_DEFAULT, S::CONST_WITH_DEFAULT);
}
17 changes: 17 additions & 0 deletions deps/examples/generic_traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
trait Test<T> {
fn test(_t: T);
}

struct SomeStruct;

impl<T> Test<T> for SomeStruct {
// note the <> in two places
fn test(_t: T) {
println!("test");
}
}

fn main() {
SomeStruct::test(1);
SomeStruct::test(true);
}
17 changes: 17 additions & 0 deletions deps/examples/newtype.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::fmt;

struct Wrapper(Vec<String>); // tuple struct wrapping the type we want to add a non-local trait to.

impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
// If we wanted the new type to have every method the inner type has, implement the `Deref` trait.

fn main() {
println!(
"{}",
Wrapper(vec!["example".to_string(), "example 2".to_string()])
);
}
8 changes: 8 additions & 0 deletions deps/examples/rpit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fn returns_closure() -> impl Fn(i32) -> i32 {
|x| x + 1
}

fn main() {
let f = returns_closure();
println!("{}", f(1));
}
31 changes: 31 additions & 0 deletions deps/examples/trait_bounds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

// Trait bounds: the `print_hash` function is generic over an unknown type `T`,
// but requires that `T` implements the `Hash` trait.
fn print_hash<T: Hash>(t: &T) {
let mut hasher = DefaultHasher::new();
t.hash(&mut hasher);
println!("The hash is {:x}", hasher.finish());
}
struct Pair<A, B> {
first: A,
second: B,
}

// Generics make it possible to implement a trait conditionally
// Here, the Pair type implements Hash if, and only if, its components do
impl<A: Hash, B: Hash> Hash for Pair<A, B> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.first.hash(state);
self.second.hash(state);
}
}

fn main() {
let p = Pair {
first: 1,
second: "2",
};
print_hash(&p);
}
27 changes: 27 additions & 0 deletions deps/examples/traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub trait Summary {
fn summarize(&self) -> String;
}

pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}

// Implement Trait on a Type
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}

fn main() {
let na = NewsArticle {
headline: "headline".to_string(),
location: "location".to_string(),
author: "author".to_string(),
content: "...".to_string(),
};
println!("Summary: {}", na.summarize());
}
10 changes: 10 additions & 0 deletions deps/examples/traits2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
trait Summary {
fn summarize_author(&self) -> String;

fn summarize(&self) -> String {
// <-- default implementation
format!("(Read more from {}...)", self.summarize_author()) // <-- can call a non-default method
}
}

fn main() {}
14 changes: 14 additions & 0 deletions deps/examples/traits3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::fmt;

trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
println!("* {} *", self); // can use println! because self is guaranteed to implement Display
}
}

// String implements Display. That would not work otherwise.
impl OutlinePrint for String {}

fn main() {
String::from("test").outline_print();
}
14 changes: 14 additions & 0 deletions deps/examples/traits4.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
trait MyHash {
fn myhash(&self) -> u64;
}

impl MyHash for i64 {
fn myhash(&self) -> u64 {
*self as u64
}
}

fn main() {
let x = 1i64;
println!("{}", x.myhash());
}
25 changes: 25 additions & 0 deletions deps/examples/traits5.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#![allow(dead_code)]

use std::clone::Clone;
use std::fmt::Debug;

// Note the `+`
fn a_function(item: &(impl Debug + Clone)) {
println!("{:?}", item.clone());
}

fn some_function<T, U>(_t: &T, _u: &U) -> i32
where
T: Debug + Clone, // note the `+`
U: Debug + Clone,
{
42
}

#[derive(Debug, Clone)]
struct S;

fn main() {
let s = S;
a_function(&s);
}
31 changes: 31 additions & 0 deletions deps/examples/traits_as_parameters.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Accepts any type that implements the specified trait:
fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}

// Trait bound syntax (mostly equivalent):
fn notify2<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}

trait Summary {
fn summarize(&self) -> String;
}

struct Article {
txt: String,
}

impl Summary for Article {
fn summarize(&self) -> String {
self.txt.clone()
}
}

fn main() {
let a = Article {
txt: String::from("some text"),
};
notify(&a);
notify2(&a);
}
Loading

0 comments on commit 77059fc

Please sign in to comment.