0
0
Rustprogramming~10 mins

Default method implementations in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a trait with a default method implementation.

Rust
trait Greet {
    fn say_hello(&self) {
        println!("[1]!");
    }
}
Drag options to blanks, or click blank then click option'
A"Hello"
B"Hi"
C"Hey"
D"Greetings"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the quotes around the string.
Using a method signature without a body.
2fill in blank
medium

Complete the code to override the default method in the struct implementation.

Rust
struct Person;

impl Greet for Person {
    fn say_hello(&self) {
        println!("[1]!");
    }
}
Drag options to blanks, or click blank then click option'
A"Welcome"
B"Good morning"
C"Hello"
D"Hi there"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the default greeting instead of overriding.
Missing the impl Greet for Person block.
3fill in blank
hard

Fix the error in the trait method signature to allow a default implementation.

Rust
trait Farewell {
    fn say_goodbye(&self) -> [1] {
        println!("Goodbye!");
    }
}
Drag options to blanks, or click blank then click option'
Abool
Bi32
C()
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Specifying a return type but not returning a value.
Using a non-unit return type without a return statement.
4fill in blank
hard

Fill both blanks to define a trait with a default method that returns a string slice.

Rust
trait Describe {
    fn description(&self) -> [1] {
        [2]
    }
}
Drag options to blanks, or click blank then click option'
A&str
B"No description"
CString
D"Default description"
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of &str as return type.
Returning a string literal without quotes.
5fill in blank
hard

Fill all three blanks to implement a trait with a default method that uses a generic type and returns a formatted string.

Rust
trait Info {
    fn info<T: ToString>(&self, value: T) -> [1] {
        format!("Value: [2]", value[3])
    }
}
Drag options to blanks, or click blank then click option'
AString
B{}
C.to_string()
D&str
Attempts:
3 left
💡 Hint
Common Mistakes
Using &str as return type but returning a formatted string.
Forgetting to convert the generic value to string.
Using incorrect format placeholders.