Skip to content

Instantly share code, notes, and snippets.

@alfateam123 alfateam123/cargo.txt
Last active Aug 17, 2017

Embed
What would you like to do?
problem with early returns in rust - `if` without `else` that returns a value
Compiling rust_problem v0.1.0 (file:///home/winter/projects/rust_problem)
error[E0308]: mismatched types
--> src/main.rs:3:3
|
3 | None
| ^^^^ expected (), found enum `std::option::Option`
|
= note: expected type `()`
found type `std::option::Option<_>`
error: aborting due to previous error
error: Could not compile `rust_problem`.
To learn more, run the command again with --verbose.
fn test(x: u32) -> Option<String> {
if x == 0 {
None
}
/*else*/ if x % 15 == 0 {
Some(String::from("FizzBuzz"))
}
else if x % 5 == 0 {
Some(String::from("Buzz"))
}
else if x % 3 == 0 {
Some(String::from("Fizz"))
}
else {
None
}
}
fn main() {
println!("Hello, world!");
println!("{:?}", test(0));
println!("{:?}", test(1));
println!("{:?}", test(3));
println!("{:?}", test(6));
println!("{:?}", test(5));
println!("{:?}", test(10));
println!("{:?}", test(15));
println!("{:?}", test(16));
}
#include <stdio.h>
// it builds just fine...
int test(int x){
if(x == 0) return -1;
if(x % 15 == 0) return 3;
else if(x % 5 == 0) return 2;
else if(x % 3 == 0) return 1;
// if I remove this line, with -Wall -Wextra I get
// a warning (-Wreturn-type) because control reaches end of non-void function
else return -1;
}
int main(){
printf("%d\n", test(0));
printf("%d\n", test(1));
printf("%d\n", test(3));
printf("%d\n", test(6));
printf("%d\n", test(5));
printf("%d\n", test(10));
printf("%d\n", test(15));
printf("%d\n", test(16));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.