fn read(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)
}
which I find readable. Comparing to another language...I haven't written Go in a while, but I think the rough equivalent would be: func Read(path *Path) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
slice, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return slice, nil
}
(Maybe in this case you'd just return the io.ReadAll rather than doing an if, but I'm trying to use similar constructs. The ? is something you can use all throughout the function, not just at the end, so I tried to match that pattern.)[edited: I said there wasn't a io.ReadToEnd extracted from io.ReadFile in Go, but jatone pointed out it's called io.ReadAll.]
(defn Read [path]
(io/ReadToEnd (os/Open path)))
Now that's what I call readable! File::open(path)?.read_to_end()
but instead read_to_end is written to take a presupplied Vec so the caller has the option to reduce allocations.Unsurprisingly APIs can be more readable when you don't ponder why they're designed the way they are and completely ignore their purpose.
The `read_to_end` API[0] was designed such that the buffer could be reused in order to avoid unnecessary allocations.
There are helpers for common tasks, though people may not know or notice them. In the case of `Read::read_to_end`, it's called std::fs::read[1], which actually preallocates the vector based on file size internally so might be faster than hand-rolling `read_to_end`.
So here's your code in Rust, for the last 3 years or so (since 1.26 was released):
fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
std::fs::read(path)
}
[0] and all of the Read trait in generalis the golang equivalent.
let bytes = std::fs::read(“path.txt”)?;
If you’re trying to actually do this in real code. The example is how you’d write this function yourself, but if you’re just trying to Get It Done, it’s significantly easier than the example. fun read(path: &Path): io.Result[Vec[UInt8] {
var file = File.open(path).orReturnErr()
var bytes = Vec.new()
file.readToEnd(&mut bytes).orReturnErr()
Ok(bytes)
}
would be good enough for me, tbh.Method syntax is reserved for functions. There are no method syntax macros. Since a return in a function terminates execution of this function, and not its caller, your example would not work.
let a: Result<u8, u8> = /* whatever *;
let b = match a {
Ok(v) => Ok(foo(v)),
e => e,
};
and transform it into: let a: Result<u8, u8> = /* whatever *;
let b = a.map(foo);
if "foo" is a macro. When you substitute "foo!" for all the "foo" above, it is obvious.await cannot be a macro, it has to be built into the language, and so it doesn't have the ! because it's not one.
"orReturnErr()" seems quite against the Rust philosophy though — refusing the method call syntax for early return means folks can easily miss something important. Rust uses ? for error handling, ! for macros, and keywords (with no parenthesis) for other control flow. I prefer it that way.
file.read_to_end(&mut bytes)?;
`bytes` is already mutable. `read_to_end` is already declared as taking a `&mut Vec<u8>`. So why force every caller to do a `&mut` un-necessarily ?By being explicit about this, Rust becomes easier to read, but (slightly) harder to write.
Because it's not unnecessary? `bytes` is a `Vec`, not a `&mut Vec`, those are different things, and Rust generally avoids magically doing things under the covers. So it doesn't auto-ref (let alone auto-mut-ref) parameters, only subjects.
Compare:
def read(path):
What is path? Unknow. What it read? Unknow. What it return? Unknow pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
What is path? Anything that can become path on the file system.What it read? Anything that can be pointed with that PATH
What it return? Vec of bytes or a IO::Error
PLUS: This code is compiled tot he exact types that call it, Path not allocate, the result can be cloned, the errors are defined in IO, ....
--
Rust is very readable: Almost any line tell you what is happening and what expect.
Where it get messy is when it hide that crucial info. But is not many times it happens.
Your example is also less about Rust and more about type signatures.
No, is HOW Rust use type signatures. Rust is in the camp of "advanced usage", not like C#, Python and others, where a "type" is barely for classification. Instead, Rust use types to inform: Memory type (heap vs stack), Cost (cheap to copy or must clone and can be potentially very big), Permisions (read/mutable), Behavior, Share-ability (can go in threads), lazy or not (iterable), etc.
It use types for a lot, and communicate much information densely.
P.D: Not always perfect and I agree that the syntax is not as nice to me, but is incredible how much you can understand from most codebases just reading, even on docs (not need IDE assistance that much)
No, I don't really agree. The example was "def read(path)", which is intentionally vague and any typed language would clarify.
Your points can be/are valid, but they don't really change the fact that the above example was a cherry pick, and Rust's (over)use of symbols and special characters make it, again, about as hard to read as one could imagine. Just because you _can_ derive meaning from it doesn't change that.
From your post:
> What is path? Anything that can become path on the file system.
> What it read? Anything that can be pointed with that PATH
> What it return? Vec of bytes or a IO::Error
Certain idioms not make much sense at first, but a big part of be on Rust is learn them. Eventually, most of it make sense and are very predictable (is incredible how much adherence exist for them in the whole community!).
Blog post idea: express this snippet (with references, aliasing control, generics and all) in pseudo C++, Java, Python, etc. Then express “reading a file in gc language with exceptions” in pseudo Rust.
pub fn read<P>(path: P) -> io::Result<Vec<u8>>
where
P: AsRef<Path>,
{
And of course if you were using a lot of u8 vec results, you might create a shorter alias for that. # Your big function has specific types
function my_function(x::UInt, y::UInt)
[ ... ]
end
# Wrapper function to minimize monomorph. cost
my_function(x::Integer, y::Integer) = my_function(UInt(x), UInt(y)) * The output type must be explicitly named instead of inferred
* The let keyword for creation of variables instead of merely assignment
* The mut keyword to distinguish between mutable/immutable variables
* The pub keyword, instead of another mechanism
* Semicolons needed after every expression
And more. Again, for every one of them, you can argue that it's _good_ for it to be there, because it serves a function. But you end up with a language with a hugely bloated syntax where the business logic is sort of swamped in these accessory keywords.That isn't syntax. It's a decision about analysis.
> The pub keyword, instead of another mechanism
The "other mechanisms" discussed are in fact not providing this feature, but pretending you needn't care, and I'd argue Rust shows that in fact you should care and pretending otherwise is a problem.
> Semicolons needed after every expression
On the contrary, semicolons are at the end of Rust's statements. If what you've got is an expression you don't need a semicolon. For example here's how log is defined on an f64 (a double precision floating point number)
pub fn log(self, base: f64) -> f64 {
self.ln() / base.ln()
}
Notice there's no semicolon there because that function is an expression, we want the value of this division as the result of the function.I don't believe Julia or Python is "best practice" over Rust. I even empathize with the opinion that explicitness may be preferential sometimes. But you _must_ be able to see how Rust's syntax overload obfuscates the core business logic, right?
Sure, business logic is more readable in something like OCaml than in Rust. On the other hand, Rust isn't really worse than something like Java, and I like having more information than what you have in Python. I'll also add that Rust is often chosen for speed and reliability, and that part of that syntax is here to guarantee that. It's not directly business logic in the traditional sense, but it's something you expect from your code.
All in all, Rust is still not at the level of the "platonic ideal for syntaxes", especially not for most of the code I write (business logic for web apps, which wouldn't need Rust's speed). Still, in the realms of programming languages that are used, it's one of the best.
FWIW `__` doesn't mean "this is part of the implementation", it means "I'm designing a class for inheritance and I don't want child classes to stop on my attributes".
No. Python certainly does not have a concept of private code[0]. The Python community has a suggestion of things being implementation details.
Surely you can see that absolutely would not be good enough for a language which strives for static correctness? And even more so as the soundness of `unsafe` blocks often relies on the invariants of the type it's used in?
[0] well that's not entirely true, I guess there's native code.
fn f(x: impl Test) { ... }
Is basically the same as fn f<T: Test>(x: T) { ... }
Having to annotate the return value of functions is partly to make sure don't break semver accidentally, but it also constrains type inference to a local search rather than global search, avoiding spooky action at distance (when modifying a function changes the signature of another function). It seems that semver hazards are more important in languages with static types.That pub? It's punching waaay above its weight! Having things private by default protects against semver hazards too, but it's also the major tool that enable writing safe code that uses unsafe { .. } blocks underneath. That's because a single unsafe block typically taints the whole module it's contained (such that even safe code needs a safety review). Being able to write safe abstractions of unsafe code is the pull of Rust so people need to get it right.
For example, setting the field len of a Vec to a value larger than what's initialized in its buffer will cause UB when accessing that memory; if this field weren't private, making a safe Vec would be impossible (likewise, a function that could set the len to any value must be private, etc).
So pub can only be used for things that are safe to export, and people should be careful with that.
Here's my least favorite syntax from there: that damn Ok(..). Ok-wrapping sucks. There were proposals to remove it, but they were rejected. There's a library that removes it [0], and people should use it. It also makes the Result<..> return type implicit in the function signature too.
[0] https://boats.gitlab.io/blog/post/failure-to-fehler/#but-abo...
Things<Like<This, That>, That> -- as in C++
Instead of a more legible (and very familiar to Rust authors)
Things (Like This That) That -- as in Haskell
Inherited from C++, we had also :: for namespacing (while a dot . could be perfectly be used for that), and tons of other stuff like <> for scoping generics.
Without some of that we could have:
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())
}
Perhaps it looks a little better? It looks for me, at least.For doing better than that we could drop C-like syntax perhaps?
The trouble is that languages have a weirdness budget - there's a finite amount of novel stuff a language can have until it becomes too weird for mainstream programmers. So language designers have to pick their weird features carefully. Spending it all in novel syntax is unwise.
I think that at the time the Rust pull was safety for low level code and, as Rust was targeted to replace some C++ components, following C++ syntax was seen as a good idea.
The syntax of type application and function application is already different in rust: F<A, B> vs f(a, b).
Type application even has default and named parameters! F<X = A, Y = B> and F<A> if B has a default.
I just think this particular type-level syntax is very noisy, specially because types in Rust tend to be very nested.
And that was a good decision. If it were too far from the C++ syntax, I would not have learned it, because as a mostly C++ guy at the time, some similarities with C++ helped me keep interest in Rust. Also, I was unable to parse Haskell's "type parameters as function applications" syntax, which was purely confusing. The Rust syntax is an abomination, that's true, but it is a necessary evil.
It's more like this,
Thing<A> becomes Thing A
Thing<A, B> becomes Thing A B
Thing<A, B, C> becomes Thing A B C
The parens only appears when you want to further nest types
And.. okay, I reckon that the Haskell syntax for types would be unfamiliar. But, at least, it's not as cluttered
let x = Foo::new();
x.bar();
Foo::bar(x);A proper language needs to allow the programmer to choose between implicit effects and explicit effects on a case-by-case basis. The reason ? is so tragic is because Rust tried to go with explicit effects only, but found that people wanted implicit effects, and ? is the closest that Rust can get. That's why it's syntactic noise: The programmer wants to get rid of it, they don't regard it as informative for this case, but they can't get rid of it.
(And checked exceptions can be perfectly well implemented with regular data, you don't need any special cases - in fact, you can do it with the same infrastructure that's already been added in a special-cased form for async/await support...)
Also, being able to call unsafe code inside unsafe functions is now considered a design mistake, and there is ongoing work to revert the default – requiring unsafe blocks even in unsafe functions: https://rust-lang.github.io/rfcs/2585-unsafe-block-in-unsafe...
[1]: https://docs.rs/anyhow/1.0.42/anyhow/trait.Context.html
Not saying it's good or bad, just how Rust ended up where it is.
I disagree it's a pejorative term as Wikipedia puts it though. Design by committee is in many cases necessary or even wanted (standard bodies).