Skip to content

Update b5.impls-and-traits.md #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions content/en/docs/b5.impls-and-traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,6 @@ fn main() {
}

// ⭐️ Implementation must appear in the same crate as the self type

// 💡 And also in Rust, new traits can be implemented for existing types even for types like i8, f64 and etc.
// Same way existing traits can be implemented for new types you are creating.
// But we can not implement existing traits into existing types.
```

## Impls & traits, without default methods
Expand Down Expand Up @@ -67,6 +63,9 @@ fn main() {
}

// 🔎 Other than functions, traits can contain constants and types.

// 💡 And also in Rust, new traits can be implemented for existing types even for types like i8, f64 and etc.
// Same way existing traits can be implemented for new types you are creating.
```

## Impls, traits & default methods
Expand Down Expand Up @@ -122,13 +121,13 @@ fn main() {
trait From<T> {
fn from(T) -> Self;
}
impl From<u8> for u16 {
//...
}
impl From<u8> for u32{
//...
}

impl From<u8> for u16 {
//...
}
impl From<u8> for u32{
//...
}
// Should specify after the trait name like generic functions
```

Expand All @@ -139,13 +138,13 @@ trait Person {
fn full_name(&self) -> String;
}

trait Employee : Person { // Employee inherits from person trait
fn job_title(&self) -> String;
}
trait Employee : Person { // Employee inherits from person trait
fn job_title(&self) -> String;
}

trait ExpatEmployee : Employee + Expat { // ExpatEmployee inherits from Employee and Expat traits
fn additional_tax(&self) -> f64;
}
trait ExpatEmployee : Employee + Expat { // ExpatEmployee inherits from Employee and Expat traits
fn additional_tax(&self) -> f64;
}
```

## Trait objects
Expand All @@ -163,20 +162,22 @@ trait GetSound {
struct Cat {
sound: String,
}
impl GetSound for Cat {
fn get_sound(&self) -> String {
self.sound.clone()
}

impl GetSound for Cat {
fn get_sound(&self) -> String {
self.sound.clone()
}
}

struct Bell {
sound: String,
}
impl GetSound for Bell {
fn get_sound(&self) -> String {
self.sound.clone()
}

impl GetSound for Bell {
fn get_sound(&self) -> String {
self.sound.clone()
}
}


fn make_sound<T: GetSound>(t: &T) {
Expand Down