Reputation: 1279
To define a function with void return, my code goes like the following:
trait Handler {
fn on_message(&mut self, msg: String) -> Result<()> {
println!("on_message: {}", msg);
Ok(())
}
}
The compiler tell me this is wrong because a Result
should always have 2 parameters:
error[E0243]: wrong number of type arguments: expected 2, found 1
--> src/lib.rs:2:46
|
2 | fn on_message(&mut self, msg: String) -> Result<()> {
| ^^^^^^^^^^ expected 2 type arguments
This confuses me. How should I define a function when I don't care about its return value?
Upvotes: 5
Views: 2382
Reputation: 139
The error message is trying to tell you that Result
takes two type parameters, i.e. Result<(), ()>
. Here's a working version:
trait Handler {
fn on_message(&mut self, msg: String) -> Result<(), ()> {
println!("on_message: {}", msg);
Ok(())
}
}
Upvotes: 1
Reputation: 58735
If you don't need error handling, then there is no need to use a Result
:
fn on_message(&mut self, msg: String) {
// ...
}
If you need to handle errors, but don't have a meaningful "success" value, then you can say that the success type is ()
, but you still need to say what the error type is:
fn on_message(&mut self, msg: String) -> Result<(), MyError> {
// ...
}
Where I put MyError
, you could use a built-in error like io::Error
, a custom error struct or enum, or any other type such as String
. It could even be ()
, making your return type Result<(), ()>
, which would let users of your function know if it was successful or not, without providing any information about either the successful outcome or the possible error. At that point, you might consider using an Option<()>
or even just a bool
, which carry the same amount of information.
Upvotes: 7