An app tells its users about news in different ways: some get an email, some get a text message, an SMS. The code that sends the news shouldn't care which kind each user picked. It only needs to know that each one can send a message. That promise is an interface.
Write:
- the interface
Notifier, with one method,send(message), which returns the text that would be sent; EmailNotifier, created byEmailNotifier::new(address), a notifier whosesendreturns"To ", the address,": "and the whole message;SmsNotifier, created bySmsNotifier::new(phone), a notifier whosesendreturns"SMS ", the phone number,": "and only the first 20 characters of the message (a message of 20 characters or fewer is sent whole);- a method
notify_all(notifiers, message)inimpl Solution, which gets a list of notifiers of any kind and returns the list of the texts they send, in the same order.
notify_all must work through the interface: it calls send on each notifier and never checks which kind of notifier it is.
Rust has no classes: Notifier is a trait, EmailNotifier and SmsNotifier are structs with a new function, and each gets an impl Notifier for ... block with its send. notify_all gets the notifiers as a &Vec<Box<dyn Notifier>>: boxes that can hold any type that implements the trait.
The program creates the notifiers listed in the input, calls notify_all once for each message, and prints each text it returns on its own line.
Example 1:
Input:
notifiers: EmailNotifier::new("ana@mail.com"), SmsNotifier::new("0712345678")
message: "Meeting at 5"
Output:
To ana@mail.com: Meeting at 5
SMS 0712345678: Meeting at 5
Explanation: The message has 12 characters, so the SMS sends all of it too.
Example 2:
Input:
notifiers: SmsNotifier::new("5550100"), EmailNotifier::new("bob@work.org")
message: "Your order has shipped today"
Output:
SMS 5550100: Your order has shipp
To bob@work.org: Your order has shipped today
Explanation: The message has 28 characters. The SMS keeps the first 20, "Your order has shipp";
the email sends all of it. The texts come in the order of the notifiers.
Example 3:
Input:
notifiers: SmsNotifier::new("111"), SmsNotifier::new("222")
messages: "Exactly twenty chars", "Exactly twenty chars!"
Output:
SMS 111: Exactly twenty chars
SMS 222: Exactly twenty chars
SMS 111: Exactly twenty chars
SMS 222: Exactly twenty chars
Explanation: notify_all is called once for each message, with the same two notifiers.
The first message has exactly 20 characters and is sent whole. The second has 21, so its "!" is cut.
Constraints:
- There are at most 50 notifiers. There can be none: then
notify_allreturns an empty list. - A message has 1 to 100 characters: letters, digits, spaces and punctuation, with no space at its start or end.
- Addresses and phone numbers have no spaces.
Free plan: 30 tutor messages. PRO is unlimited.
