JS
function max(a, b) {
if (a < b) {
return b;
}
return a;
}
console.log(max(1, 2));
// 2
console.log(max(2, 1));
// 2
console.log(max([1,2,3]));
// [1,2,3]
Rust fn max<T: PartialOrd>(a: T, b: T) -> T {
if a < b {
b
} else {
a
}
}
println!("{}", max(1, 2));
// 2
println!("{}", max(2, 1));
// 2
println!("{}", max([1, 2, 3]));
// Compiler error
In JS, it would be prudent to test for reasonable misuse of this kind (return undefined, throw Error, etc). The author claims _This is a dynamically typed language. You get exceptions when you mess up the types._ That isn't true in this case and it is not clear from the code what would/should happen.In rust, you don't need any tests like this.