Define a Summarizable Trait in Rust
Traits in Rust allow you to define shared behavior that can be implemented by different types. This challenge will test your understanding of defining a trait with a method and then implementing that trait for a custom struct.
Problem Description
Your task is to create a Rust trait named Summarizable. This trait should define a single method called summary that takes no arguments and returns a String. The summary method should generate a concise string representation of the object it's called on.
You will then need to define a struct called Article which has a title (String) and content (String) field. Finally, you will implement the Summarizable trait for the Article struct. The summary method for Article should return a string in the format: "Article: [title] - [first 50 characters of content]". If the content has fewer than 50 characters, the entire content should be used.
Examples
Example 1:
Input:
let article = Article {
title: String::from("Rust Traits Explained"),
content: String::from("Traits are a powerful feature in Rust that allow you to define shared behavior across different types. They are similar to interfaces in other languages but with additional capabilities. This article will delve into the intricacies of defining and implementing traits."),
};
// Call the summary method
let summary_string = article.summary();
Output:
"Article: Rust Traits Explained - Traits are a powerful feature in Rust that allow you to define shared behavior across different types."
Explanation:
The summary method for the Article struct correctly formats the output by including the title and the first 50 characters of the content.
Example 2:
Input:
let short_article = Article {
title: String::from("Brief Note"),
content: String::from("This is a very short piece of text."),
};
// Call the summary method
let summary_string = short_article.summary();
Output:
"Article: Brief Note - This is a very short piece of text."
Explanation: Since the content is less than 50 characters, the entire content is included in the summary.
Constraints
- The
titleandcontentfields of theArticlestruct will always beStringtypes. - The
summarymethod must return aString. - The generated summary string must strictly adhere to the specified format.
Notes
- Consider how to handle slicing strings in Rust to extract the first 50 characters.
- Remember that traits are defined using the
traitkeyword. - Implementing a trait for a struct is done using the
impl TraitName for StructNamesyntax. - You will need to use methods available on the
Stringtype to achieve the desired output.