by gardaani · 3y ago · 0 comments
public func read(path: AsRef<Path>) -> io.Result<Vector<u8>> {
func inner(path: &Path) -> io.Result<Vector<u8>> {
var file = File.open(path)?;
var bytes = Vector.new();
file.readToEnd(&mut bytes)?;
return Ok(bytes);
}
return inner(path.asRef());
}
I have replaced pub with public, replaced fn with func, removed separate declaration for P, replaced :: with ., replaced Vec with Vector, replaced let mut with var, replaced snake_case with camelCase, added return keywords. Note that all these are syntax changes. Semantics hasn't been changed at all. One more thing would be to remove the semicolons..Compare that to the original. Which one is more readable?
let (a, mut b) = //some tuple
You can't just replace `let mut` with `var` because it changes the semantics of the code.> Which one is more readable?
Not seeing any difference.
fn foo(x: u8) -> u8 {
let y = {
let z = something();
x + z
};
y
}
TL;DR: It's not a property of the function, it's a property of the curly braces. pub fn read(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
in Rust without needing to declare P separately.* Is this function monomorphised for each type passed in or is the argument passed in as a trait object? If the latter, does it implicitly fall back to monomorpisation if the trait is not Object-safe(e.g. it takes or return `Self` by ownership)? How do we specify which of the two to use when we need to for performance reasons?
* Let's say we have a function with two inputs: `func foo(a: SomeTrait, b: SomeTrait)` How do I specify that both inputs must be the same type?
Here's a demonstration of the difference: https://play.rust-lang.org/?version=stable&mode=debug&editio...
fn poly(a: impl Display) {
println!("{a}");
}
instead of just fn poly(a: Display) {
println!("{a}");
}
Can I use same identifier for type and trait at the same time? use std;
use std`fs`File;
pub fn read<P: AsRef<Path>>(path: P) -> io`Result<Vec<u8>> {
fn inner(path: &Path) -> io`Result<Vec<u8>> {
let mut file = File`open(path)?;
let mut bytes = Vec`new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
inner(path.as_ref())
} public func read(path: URL) throws -> Array<UInt8> {
let file = try FileHandle(forReadingFrom: path)
let bytes = try file.readToEnd() ?? Data()
return Array(bytes)
}
Yes, the example above is not generic and not even idiomatic Swift, but it's a good glimpse into how Rust could look like.Hopefully someday Swift would become more safe, less tied to ObjC legacy and actually cross-platform. It's a shame that such a nice language is basically Apple-only.
But sure, there are a lot of interesting languages out there. I would love to use something other than Rust, but there are simply no choice.