180 points · by lengads · 13y ago · 102 comments
let computed_key = match (key.len() > self.block_size, key.len() < self.block_size) {
(true, false) => self.zero_pad(self.hash(key).digest),
(false, true) => self.zero_pad(key),
(false, false) => key
}
At least there is some matching here, unlike in the original example. But in real world this should be if..else if..else statement, not match - the latter being used makes no sense if there is no matching going on. In Erlang there is an if statement, which is a 'case' (equivalent of match here) but with matches taken out and only guards allowed - that's what would fit here, but I doubt Rust has something like this.Also, does the compiler complain about my example above being not exhaustive? I think in OCaml it would, which is sometimes nice.
Oh, but it does! There's the cond! macro:
let computed_key = cond!(
(key.len() > self.block_size) { self.zero_pad(self.hash(key).digest) }
(key.len() < self.block_size) { self.zero_pad(key) }
_ { key }
);Idris [3] is another language with dependent types (and is more Rust-like) designed for systems programming. I don't think Idris has type level presberger arithmetic though making some things a bit verbose.
[1] http://www.ats-lang.org/ [2] http://bluishcoder.co.nz/2010/09/01/dependent-types-in-ats.h... [3] http://www.idris-lang.org/
I am familiar with ATS and I don't like that I am only familiar with it from the Language Shootout contest website. I haven't heard of it used in production, no blogs, no news on HN.
It is a bad excuse and rather sad but my main charge against it is that it is not popular enough.
Yes, although the error message isn't very good:
crypto.rs:55:23: 59:5 error: non-exhaustive patterns: true not covered
crypto.rs:55 let computed_key = match (key.len() > self.block_size, key.len() < self.block_size) {
crypto.rs:56 (true, false) => self.zero_pad(self.hash(key).digest),
crypto.rs:57 (false, true) => self.zero_pad(key),
crypto.rs:58 (false, false) => key
crypto.rs:59 };
error: aborting due to previous error
And technically that's not a good thing, since (true, true) is not possible considering the input. match key.cmp(self.block_size) {
Equal => ..
Greater => ..
Less => ...
}
Which is much prettier (and more succinct) than both your original code and my example. You could also use a `cond!()` macro here, but that would mean you don't have an example for a blog post, so I think the above code is the best option. Thanks to kzrdude for posting.The second sentence:
> I want a language where I can be much more productive than in C: one in which I do not fear the correctness of my memory management, and don’t have to go through major gyrations to write concurrent code.
And we see no explicit demonstrations of the memory management and no demonstrations at all of the concurrency model. It feels like the author had a more fleshed out post in mind, but either decided it was running too long or got bored before reaching the conclusion. :\
Or it could be that this post is just the beginning of his journey of learning & blogging about Rust. He did post another one 4 days later, albeit not yet touching on the topics you mention:
http://relistan.com/a-pattern-for-wrapping-c-function-calls-...
I've been looking into Rust during the past few days and I must say I got stuck on the memory model - all the different pointers and their interaction with ownership and mutability, closures capturing their environment (variables outside the closure in the scope where the closure is defined), reference binding, and then things like std::Cell which on the one hand seems to be an alternative to std::Option but on the other hand it's using some unsafe operations in its implementation to change mutability or something... It's quite confusing and it stopped me from writing a simple example application I wanted to write because I wanted to understand what's going on a bit better first.
@ is going to sink into the library and will be deemphasized in the language to help with this. That leaves only ~ (pointers) and & (references).
> closures capturing their environment (variables outside the closure in the scope where the closure is defined)
Right, this is one of the difficult pieces. This is going away as well in favor of Java-like Runnables to make the variable capture easier to understand (with macro sugar to make them just as convenient as closures). The closures that remain will work just like the closures you know from other languages regarding variable capture, and the Rust-specific stuff regarding variable capture will be gone.
> std::Cell
Yeah, this needs to be better documented. Part of the problem is that we haven't totally nailed down what Cell will be used for yet.
1. avoid dynamic allocations (limit yourself to stack-only objects) and you'll get rid of those fears for memory management
2. limit yourself to functional programming and you'll get a pretty good concurrent-ready code
For this "I need a new language" stance you'll need some better reasons.
Rust is a longer-term, more ambitious effort.
The situation with Go is completely different. Go is just... meh. Its concurrency model is worse than Erlang's, which predates it. Its type system is worse than Standard ML's, which predates it. Its runtime efficiency is noticeably worse than C++'s, especially so when using customized allocators and avoiding exceptions and RTTI. In short, Go is mediocre.
Modula-2, Ada, Turbo/Apple Pascal were there first, but sadly lost developer hearts to C.
let computed_key = if key.len() > self.block_size {
self.zero_pad(self.hash(key).digest)
} else if key.len() < self.block_size {
self.zero_pad(key)
} else {
key
}The idea is that while you may be able to traverse code-paths with side effects in some of these languages, they encourage treating a line of code (term used loosely, as an expression can span multiple lines) as a computable value. It may take a bit of getting used to at first, but from my own experience, it now feels weird and awkward when a language doesn't.
Reminds me of looking at a nasty language like MUMPS or something, where persistence is built into the core language; statement-oriented languages tend not to be composable.
However, I want to question the claim:
> Go is also not particularly friendly to interface to external libraries written in C
which doesn't seem to be explained anywhere in the article, and jars with my understanding.
Go does play very well with C; cgo[0] makes this pretty straightforward.
Maybe there are specific things that the author is trying to do that they found difficult in Cgo, but I would say that Go does play fairly nicely with C; that was a design goal.
Here's a simple example of cgo in action: http://golang.org/doc/articles/c_go_cgo.html. As you can see, it's relatively straightforward and easy to use.
So Go applications are something like "compiled, fast Ruby or Python." As far as I understand, Rust should theoretically be a way to write a piece of your application (even mainly C application) in something that gives you a different kind of expressibility. If there's need for that is another question, specifically, I'd like to see some examples that would really impress me. The examples the article author provided give me only the impression "OK it's weirder syntax but it's not so far from what would have to be written in C anyway, so where's the advantage?"
What I consider missing for "properly" interfacing with C is for Rust to be able to slurp C headers as they are, without the need for additional "translation" files that are presented in the article. At least the headers without the definitions of the functions. But the declarations of the structures and functions and even basic preprocessing were really, really convenient.
Memory safety.
https://github.com/mozilla/rust/blob/master/src/libextra/jso...
I know it's the least interesting thing, but for me the simplest rule to recognize Rust vs Go is that at the moment Go has the nice and minimalistic := and Rust the clumsy (for my aesthetics at least) "let."
Still, I understand that Rust attempts to solve more than Go in some aspects, and I really hope it can succeed. For that, yay Rust!
Can somebody explain me the reason for constructs like this:
self.error(~"trailing characters")
vs self.parse_ident("ull", Null),
I read that ~ means "owned box on heap." Why should something that are facto string literals be owned and on heap? Isn't the need to allocate and box string literals on the heap something that makes the language unnecessarily slow? And why there's a need somewhere to explicitly box something that's known at the compile time and somewhere there isn't?It is not possible for us to have ":=" because we don't know whether to parse a pattern or an expression without a prefix token like "let". Rust's pattern language is far more expressive than Go's and one grammar will not cover both.
> Why should something that are facto string literals be owned and on heap? Isn't the need to allocate and box string literals on the heap something that makes the language unnecessarily slow?
Probably the `error` method explicitly asked for a heap-allocated string, perhaps because it wants to pass it to someone who will later free it. (Unlike in C, it would be a type error to attempt to free a constant string in read-only memory, which is what a plain string literal is in Rust.)
The "error" function returns a struct containing the error string. I suspect the intention is to allow dynamically constructed error messages like "syntax error at line 4, char 3" (although it doesn't seem to be doing this anywhere). Since the string might be dynamically allocated, it has to be freed when the struct is freed, which obviously can't happen if the struct just has a pointer to the literal in static memory. (You could flag the string somehow as "should be freed/should not be freed", as you suggest in your other comment, but this has its own tradeoffs)
If you wanted an "error" function that would take string literals directly (and only string literals) you would do something like this: https://gist.github.com/bct/6300740
The "parse_ident" function doesn't return any portion of the input string, so it can just use a borrowed reference.
> What I consider missing for "properly" interfacing with
> C is for Rust to be able to slurp C headers as they are,
> without the need for additional "translation" files that
> are presented in the article.
rust-bindgen (modeled after Clay's bindgen tool) has you covered:https://github.com/crabtw/rust-bindgen/
C header files go in, the proper Rust definitions come out. There are long-term plans to adopt this as an official tool to be distributed with the compiler.
That is correct, but the GP is correct as well. Using C code in Go is easy(just use cgo etc.), vice versa not so much(no such thing as goc etc.).
Rust can operate without garbage collection if you don't use shared pointers.
> "OK it's weirder syntax but it's not so far from what would have to be written in C anyway, so where's the advantage?"
Apart from memory safety, a lot of exciting, modern features: pattern matching, typeclasses, immutability per default, built-in concurrency and parallelism, a module system, a packaging system...
> What I consider missing for "properly" interfacing with C is for Rust to be able to slurp C headers as they are, without the need for additional "translation" files that are presented in the article.
I don't know any language with this kind of FFI...
Does Objective C count?
Note that this is not just a matter of Go's GC and runtime requirement, but simply the fact that they do not support cdecl / stdcall conventions.
There are plenty of garbage collected languages that can be linked into a C program (Lua, Python, even Haskell) - you just have to make extra calls to start-up the runtime.
"Why for instance is it not a good idea to write a library in Go? The reason for this is that Go for needs quite a heavy runtime that does garbage collection and provides a scheduler for it's coroutines."
[0] http://lucumr.pocoo.org/2013/8/18/beautiful-native-libraries...
Eventually once all of our LLVM patches are upstream and the versions including the patches make it into common repositories you may be able to use your system LLVM to compile the Rust compiler, at which point the compile times will drop dramatically.
We continue to work on compile speed of Rust code all the time.
Call me spoiled but I expect a one-click installer in this day and age. I still haven't tried to actually use Rust because of that and I am sure I am not the only one.
But, windows is (unfortunately) a bit of a second class platform at the moment (although there have been some very big strides in the last week or so). So part of the reason for poor windows packaging is Rust isn't ready on windows yet (even more so that its normal pre-alpha-ness on Linux and Mac).
It will come in its due time.
Every time I update my netbook with a new Rust release it takes a few hours, it almost feels like I am compiling KDE or something.
- it has to build LLVM: Rust currently has to use a custom version; the goal is for this to be unnecessary so that the system LLVM is ok.
- it has to build itself and the standard libraries 3 times: rustc is written in Rust; so it has to bootstrap.
- it eats a lot of memory, so bootstrapping on low memory systems is bad. Much of this is historical; the bootstrapped code means that large portions of the compiler are written when the language was less developed, and so is very non-idiomatic. It's progessively being modernised
The first and last can be fixed; the second can't, at least until there are binary releases.
struct Digest { digest: ~[u8] } // what's ~ here?
for self.digest.iter().advance |&byte| { acc = acc.append(fmt!("%02x", byte as uint)); } acc
What does the above mean? acc as a separate line and nothing else
I hate it when people reinvent the same construct that can be found in other languages but differently. I guess they want to do something different in their language, is it?
The `~[u8]` would be written `std::unique_ptr<u8>` in C++. They're used everywhere in Rust, and having to write out unique_ptr would get awfully tiresome.
The `acc` on its own line is a result of "the last statement gets returned" like many functional languages do. If you were writing C++, you'd write `return acc;` instead. This one is more of a convenience, and you could get away without it.
Wouldn't it be `std::unique_ptr<std::vector<u8>>`?
(1) Still being worked on.
fn hexdigest(&self) -> ~str {
let mut acc = ~"";
for &byte in self.digest.iter() {
acc.push_str(fmt!("%02x", byte as uint));
}
acc
}~[T] is just a vector.
There's also the advantage that there's no way to conflict with the * multiplication operator.
~ is an owned pointer (like unique_ptr in C++); & is a "reference" or borrowed pointer (allowing access to data without taking ownership); * is a raw/unsafe pointer, and is identical to C's pointers.
Also, the * pointer doesn't conflict with multiplication because they can never occur in an ambiguous context:
foo * bar = NULL; // C
let bar: *Foo = std::ptr::null(); // Rust
let bar = std::ptr::null(); // Rust, using type inference