10 ms·
Thoughts on Rust, a few thousand lines in
- shepmaster 8y ago> the escape hatch suggested on the internet, `partial_cmp(...).unwrap_or(Ordering::Less)` This is often a Bad Idea, as you get unstable sorts and you are right back to the same problem. - Explanation: How do I get the minimum or maximum value of an iterator containing floating point numbers? — https://stackoverflow.com/a/50308360/155423 https://stackoverflow.com/a/50308360/155423 - Example: https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=d459a0de3fc4dce15a090d078cf8f15e https://play.integer32.com/?version=stable&mode=debug&editio... See also: - How to do a binary search on a Vec of floats? — https://stackoverflow.com/q/28247990/155423 https://stackoverflow.com/q/28247990/155423 Instead, use a wrapper type or raise a panic.
- stabbles 8y agoIsn't there a default total order for floats? E.g. -Inf < -1.0 < -0.0 < 0.0 < 1.0 < Inf < NaN?
- achamayou 8y agoNo, because x < NaN and x > NaN are false for any value of x.
- stabbles 8y agoYes, the literal < in the language induces a partial order by convention. What I'm getting at in my comment is that you can define a sensible total ordering.
- wyldfire 8y agoThe challenge becomes what code to emit when you see those operators: native target comparisons, or the software implementation of your total ordering? The latter is safe and slow and the former is fast and IMO idiomatic. So since no one needs this often enough to emit the soft-float comparison code, we should emit the fast code. If folks need different behavior they should use different types. This is similar to the behavior with integer overflow, which you can opt into by using checked types or checked operations. Though in rust we have a convenience that the overflow-detecting code is emitted for debug targets.
- deleted 8y ago[deleted]
- achamayou 8y agoIt is possible to do redefine NaN as something different than what IEEE 754 contains, but it will surprising to some users, and it will come at a performance cost because you can no longer let the hardware handle all float comparisons directly.
- qznc 8y agoYes, there is: https://en.wikipedia.org/wiki/IEEE_754#Total-ordering_predicate https://en.wikipedia.org/wiki/IEEE_754#Total-ordering_predic... It is not something to use by default though. It is implemented in software and thus a lot slower than the hardware comparison.
- dkarl 8y agoI'm curious as to why it isn't implemented in hardware. Is it really so rare to need to sort floats, or so common to need a different ordering when you do?
- stabbles 8y agoOf course sorting floats happens a lot. In practice one rarely encounters NaN's and ±Inf's, so fast comparison for concrete values is the default. I don't know why the 'slow' total order is not implemented in hardware though. But fortunately in comparison sort algorithms that run in O(n lg n) you can get away with doing an O(n) partitioning of the array into [-, +, NaN] and then applying a fast integer comparison operator to the negative values (-) and positive values (+). In fact the above idea ties in neatly with QuickSort, which is already based on partitioning & sorting recursively.
- bsder 8y ago> Of course sorting floats happens a lot. Is this true? I am actually struggling to remember the last time I did a sort with a float/double as the key--especially in a performance bounded context ... <thinking> ... Aha. Graphic engine. Octtree with coordinates. I really had to think about that. So, I'm a bit skeptical of float sorting happening a "lot". Is this perhaps an ML primitive somewhere?
- harrisi 8y agoLanguages that only have floats, such as JavaScript and Lua, certainly sort floats quite often.
- rusbus 8y agoOP here -- this post is pretty dated. I currently use the OrderedFloat [1] crate to solve this problem which works quite well and plays nicely with NaN https://crates.io/crates/ordered-float https://crates.io/crates/ordered-float
- IshKebab 8y agoTo me this feels quite pedantic. Being able to do less than on NaNs and just having it do something vaguely sensible (as in your linked solution) is a far more common requirement than need to handle NaNs specially. You could even say the reason NaN exists is so that you don't have to check for NaN constantly. Rust is being technically correct but practically really annoying, for basically no benefit.
- steveklabnik 8y agoFor what it's worth, many in the Rust community agree with you. Many people consider this a mistake, in hindsight, though not everyone.
- cryptonector 8y ago> Unlike nearly every language I’ve ever used, Rust actually encourages variable shadowing. Haskell does it too, for the same reason/purpose / with the same effect.
- favorited 8y agoSwift does, but typically for Optional promotion. You see stuff like `guard let delegate = delegate else { return }` inside functions all the time, shadowing a property with a local & promoting the type from Optional<T> to T. It's not the same as the Rust example because you're shadowing an ivar to a local, but since `self.` is implicit you're still shadowing.
- shepmaster 8y ago> for Optional promotion You'll see the same in Rust fn example(name: Option<String>) -> Option<usize> { let name = name?; Some(name.len()) } Or fn example(name: Option<String>) { if let Some(name) = name { println!("{}", name.len()); } } A main difference is the requirement to use `Some`, which allows for the flexibility to apply to any enum. > but since `self.` is implicit To make sure I'm following, do you mean that Rust's `self.` is implicit in Swift?
- mlex 8y agoYeah `self.` is implicit. In Swift: struct S { var string: String func doSomething() { // These two lines are equivalent. print(string) print(self.string) } }
- favorited 8y agoThat all makes sense. I've only done a couple days of Rust, so my recollection is spotty. The shadowing makes sense because if a local variable was moved out, then you're not really shadowing it anymore. Is my understanding of that correct? > do you mean that Rust's `self.` is implicit in Swift? Swift's `self.` is implicit in Swift – in most contexts, to access a property the `self.` is not required. `self.name = "John"` and `name = "John"` are equivalent (assuming self is an object with a name property). There are places where explicit `self.` is required though – when you want to differentiate between a shadowed local and a property (obviously), or when you're inside a closure (to make it clear that the closure is capturing self, not just capturing a reference to the property).
- cryptonector 8y agoThis makes me want to add `p90`, `p50` and so on to jq...
- StreamBright 8y agolet foo = "..."; let foo = parse(foo); let foo = escaped(foo); Is it really shadowing or mutation of foo? I would consider this shadowing (something you can do in OcaML): let foo = "..." in let foo = parse(foo) in let foo = escaped(foo) in dosomething(foo);;
- UK-Al05 8y agoYou can't mutate variables in rust without declaring mut
- StreamBright 8y agoBut how do you know just by reading that code? It would not be obvious to me at all.
- goto11 8y agoYou mean if you don't know the language?
- StreamBright 8y agoI guess I just need to learn Rust. I wouldn't write a style of code where I have 3 lets after an other and using the same variable name.
- bryal 8y agoI think it's quite fine to assume the reader knows enough rust to know the difference between mutable and immutable variables.
- empath75 8y agolet foo = bar; let foo = bat; is shadowing let foo = bar; foo = bat; is a compilation-time error because foo isn't mutable. let mut foo = bar; foo = bat; is reassignment. in working code, either foo is declared as mutable or it's not, and it's pretty obvious from the code what's happening.
- cphoover 8y agoI've not done any rust dev before but the whole variable shadowing thing really scares me, in that it makes it not obvious where the initial declaration comes from. This seems difficult to reason about.
- bluejekyll 8y agoTwo things, 1) the compiler doesn’t really allow you to screw it up in really scary ways, but you can I suppose. 2) it allows you to rebind a variable name to a new type, of a new state during execution without coming up with a hokey name for the new thing that’s really just the original modified in some way.
- gpm 8y agoI've done a fair bit of rust development and never found that to be an issue. It probably helps that the only ways to introduce new variables are all very distinctive: let [new variables] = [expr]; if/while let [new variables] = [expr] { [new variables scoped here] } for [new variables] in expr { [new variables scoped here] } fn name([new_variables]) { [new variables scoped here] }
- Thiez 8y agoYou forgot `match` and closures. But in general I think new variables can be created in all contexts where a pattern can be used.
- steveklabnik 8y agoYes, in fact, it's always a pattern. Even let x = 5; is a pattern, just a very simple one!
- zackpierce 8y agoThe good news is that if you want to disallow shadowing in your codebase, there are optional clippy lints that can be applied at compile-time.
- int_19h 8y ago
- KenanSulayman 8y ago> A lot of great, well loved, crates don’t have a lot of Github stars. This was a really important learning for me. When I'm looking for crates to solve a problem and there's only a handful of them, I almost always go through every single one of them, even if some have thousands and the others only tens of downloads. It's an incredible feeling to find those unknown diamonds..
- siscia 8y agoMake sure to thanks the maintenars of those repo. It really help!
- _hardwaregeek 8y agoRust is one of the few times where the language/ecosystem does precisely what I wished it would do. For instance, being able to partially destructure JSON into a struct in a typesafe manner is just awesome.
- EwanToo 8y agoThis sounds really useful, you don't happen to have an example of this do you? Thanks in advance!
- rusbus 8y agoHi -- OP here. I actually do it in the tests (but for TOML): https://github.com/rcoh/angle-grinder/blob/master/tests/integration.rs#L10-L16 https://github.com/rcoh/angle-grinder/blob/master/tests/inte... https://github.com/rcoh/angle-grinder/blob/master/tests/structured_tests/count_distinct.toml https://github.com/rcoh/angle-grinder/blob/master/tests/stru...
- deleted 8y ago[deleted]
- _hardwaregeek 8y agoI’m basically talking about Serde. Read the section titled “Parsing JSON as strongly typed data structures”. What’s nice is that you don’t have to include all the fields in the JSON in the struct. Serde will only give you the ones defined by the struct. https://github.com/serde-rs/json/blob/master/README.md https://github.com/serde-rs/json/blob/master/README.md
- hu3 8y agoI'm not sure I'd consider that lib any safer than the average serialization library when things like this happen: https://github.com/serde-rs/json/issues/464 https://github.com/serde-rs/json/issues/464
- throw0u1t 8y agoOne thing I don't like about Rust is how taking a slice of a string can cause a runtime panic if the start or end of the slice ends up intersecting a multi-byte UTF-8 char. I would prefer it if this feature didn't exist at all rather than cause runtime panics. https://play.rust-lang.org/?gist=e02ce5e9aacfee3a2b4917d5624b9ec1&version=stable https://play.rust-lang.org/?gist=e02ce5e9aacfee3a2b4917d5624...
- dbaupp 8y agoString slicing using byte indices has to exist in some form, since it is the only thing that is efficient (O(1)). But, I guess it could have used syntax other than somestring[...].
- throw0u1t 8y agoIt could slice on bytes and return a slice of bytes since the String type is a wrapper over Vec<u8>.
- dbaupp 8y agoThat means one loses all the conveniences and guarantees of the string types and, in many cases, forces an immediate revalidation the byte slice as UTF-8 to get back to &str, which is O(n). Furthermore, this is also rather clunky. I suppose one could have it return StrWithInvalidSurrounds, where just the first (at most) 3 and last (at most) 3 bytes might be invalid, which would then allow for O(1) revalidation to a &str, and even other operations like continuing to slice... But this is even more clunky for actual use! I think a moderately less clunky API might have been to not use integers for byte indexing, but instead some ByteIndex wrapper type that string operations return, meaning one can't just write `s[..5]` in an attempt to get the first 5 characters of the string. (Also, there's str::get that returns an Option: https://doc.rust-lang.org/std/primitive.str.html#method.get https://doc.rust-lang.org/std/primitive.str.html#method.get )
- int_19h 8y agoIf you want to just slice on bytes without any String semantics, why not use Vec<u8> then? String implies that it is, well, a string.
- kazinator 8y ago> Like Go, Rust can compile statically linked linux binaries. The GNU C library (needed not only by C programs for C things) doesn't support static linking, so the only way this is possible is to use another library entirely, or raw inlined syscalls (where applicable).
- steveklabnik 8y agoYes, we have full support for MUSL. It's a $ rustup target add x86_64-unknown-linux-musl $ cargo build --target x86_64-unknown-linux-musl away.
- ekidd 8y agoYeah, Rust's musl support is great. We use it heavily at work for all sorts of CLI tools. Many thanks to everybody who worked on this. (And if you need to link against common C libraries like OpenSSL or PostgreSQL, I maintain a Docker image with the necessary C toolchains, and instructions on how to use it: https://github.com/emk/rust-musl-builder https://github.com/emk/rust-musl-builder. There are a couple of similar images out there, too, I think.)
- throwaway23H 8y agoYou can also download the cross-compilation tarball for musl at https://static.rust-lang.org/dist/rust-std-1.31.0-x86_64-unknown-linux-musl.tar.gz https://static.rust-lang.org/dist/rust-std-1.31.0-x86_64-unk... if you installed rust that way. You'd then build normally: $ cargo build --target x86_64-unknown-linux-musl
- dbaupp 8y agoRust's main toolchain has first class support for musl: https://rust-lang-nursery.github.io/edition-guide/rust-2018/platform-and-target-support/musl-support-for-fully-static-binaries.html https://rust-lang-nursery.github.io/edition-guide/rust-2018/...
- jabl 8y agoBy default rust links dynamically to glibc, while rust stuff is statically linked. Which I think is a reasonably good default. Most Linux systems provide glibc, and you can deploy binaries to them without those systems needing a rust installation. Of course, there's the usual issue with glibc symbol versioning, so you probably want to build your binaries on the oldest supported system (say, a centos 6 container).
- ilovecaching 8y agoI'm a network engineer, and I've done C++ for over a decade now. One of the nice things about Rust is that they decided to go with async over fibers, which is in line with how most high performance C++ is written. The Rust team also isn't rushing Future out the door, so it's coming along much nicer than the C++ Future, which is usually replaced because it's not monadic. Rust is great, and I highly recommend learning Rust if you want to become a better C++ developer. C++ introduces a lot of unnecessary headaches Rust completely solves. Rust is worth the switch if only because reading error messages from expanded templates is horrible compared to type system that actually understands type parameters. I'm really bullish on Rust becoming even more mainstream, to the point anyone can pick it up and use it in their business without a second thought by 2020.
- f2f 8y agoi admire you: you change your occupation every couple of days, as well as the languages you've replaced rust for :)
- daboross 8y agoCould you site this? I've looked at ilovecaching's comment history (at least up to ~60 days ago) and they seem consistent on being a networking programmer who uses C++. Was there a particular comment you found which would indicate this isn't the truth?
- f2f 8y agonb: you mean "cite". why would you make me do this? you can doxx people on your own dime... still, for posterity: https://news.ycombinator.com/item?id=18328964 https://news.ycombinator.com/item?id=18328964 "...now I am working full time as a Rust developer" https://news.ycombinator.com/item?id=18310666 https://news.ycombinator.com/item?id=18310666 "As a long time Erlang developer..." https://news.ycombinator.com/item?id=18265199 https://news.ycombinator.com/item?id=18265199 "As someone who has worked two jobs now writing, deploying, and operating Erlang clusters, I recommend switching to Rust." https://news.ycombinator.com/item?id=18251478 https://news.ycombinator.com/item?id=18251478 "Becoming a professional Haskell and Erlang developer really shifted my view on OOP" https://news.ycombinator.com/item?id=18185795 https://news.ycombinator.com/item?id=18185795 "I've been using Rust in production for a little over half a year, and my team and I have run into very few issues. [...] We're all extremely glad we chucked C++ and Go and switched to Rust. " https://news.ycombinator.com/item?id=18171917 https://news.ycombinator.com/item?id=18171917 "I am exclusively using Go and Rust at home and at work, and I find myself equally productive in both." you get the point.
- bqkfbe 8y agoWow the Rust hype is really an echo chamber right now. Seems very academic and nobody really seems to be using it in production..
- nicoburns 8y agoQuite a few people are using it in production: dropbox, npm, and I believe amazon and microsoft. I've used it in production, and subjectively it was much easier to work with than C++.
- steveklabnik 8y agoAmazon and Microsoft both are, yes.
- GolDDranks 8y agoExcept for Dropbox, Amazon, Microsoft, Google, Mozilla...
- dkarl 8y agolet foo = "..."; let foo = parse(foo); let foo = escaped(foo); ... doSomethingWith(foo); I don't see how this is helpful for avoiding the bug described. The most common bug with this type of code is mistaking which form "foo" represents at a given line of code, or that form changing as the code evolves. For example, if one programmer writes let foo = "..."; let foo = parse(foo); ... doBarWithFoo(foo); and another programmer comes along, doesn't notice the call to doBarWithFoo, and needs an escaped version of foo: let foo = "..."; let foo = parse(foo); ... let foo = escaped(foo); doBazWithFoo(foo); ... doBarWithFoo(foo); // This still looks correct in isolation This is a classic problem with mutable variables that frequently causes hard-to-spot bugs. Whereas if each form has a distinct meaningful name, this change wouldn't introduce a bug, and if somehow a bug were introduced, good names will make it possible to spot even considering the line in isolation: doBarWithFoo(fooEscaped); // Hey! The input to doBarWithFoo shouldn't be escaped! If the only useful form of foo is the final one, then you can avoid having accessible names for the invalid intermediate forms like this: let foo = escaped(parsed("...")); Or like this for more complicated logic (I'm not a Rust programmer (yet) so this may not be the right syntax): let foo = { // Complicated logic finalForm; }; I feel like if I ever write a lot of code in Rust I'll find a linter rule that warns about shadowing variables and use it religiously. But maybe I'm missing a use case where it's crucial.
- wilg 8y agoI think the example only really works if `parse` and `escaped` return something other than a string. If that was the case, the type system will save you.
- moosingin3space 8y agoIn your particular example, the ownership system would help here, since `foo` is consumed by `doBazWithFoo`. (Only exception is when `foo` is `Copy`.)
- Misdicorl 8y agoI believe the way this is solved is by having the type of escaped(foo) different than that of parse(foo) and only accepting a EscapedString in doBaz and an ParsedString in doBar. Your type structure at no extra runtime cost is String : ParsedString : EscapedString. This ensures you don't escape strings before parsing them too. Nice!
- wyldfire 8y agoGreat job. Just a nit/request for that gif illustrating agrind's use -- I keep watching it to see what args you've passed to see how it's being used but the output finishes and loops before I understand what I'm seeing. Not sure if it's a property of the image or my browser but if you can turn off the looping in the image that might work better. Or add static frames at the end for the slow folks like me ;)
- vmarsy 8y agoOne thing Rust doesn't seem to be doing very well yet is guard clauses, specifically when handling Option<T>. I've seen and appreciated the use of guard clauses in many languages, as a good way to quickly check for a few conditions at the top of a function, and return early if those conditions aren't met. Since it seems that Option<T> are recommended in Rust, there's a lot of time you want to quickly return if `Some(x)` is not here (i.e. it's `None`), and if it's here, continue through the function, without having an unnecessary indentation from an extra brackets. There seem to be a good amount of smart discussion into handling those [1][2]. some threads are more than a year old, but it seems to be making progress. [1] https://github.com/rust-lang/rust/issues/45978 https://github.com/rust-lang/rust/issues/45978 [2] https://internals.rust-lang.org/t/pre-rfc-allow-pattern-matching-after-guard-clause/6238 https://internals.rust-lang.org/t/pre-rfc-allow-pattern-matc...
- oleganza 8y agoI'm using `.ok_or(SomeError)?` which converts Option into Result and opens Ok() for the rest of the scope, short-circuiting on Err(). I know about Swift's `guard` statement, but I never had a case yet when I didn't want to return Result in such kind of code, so ok_or was working for me well.
- steveklabnik 8y agoYou can use ? on an Option if your type returns an Option. If it returns a Result, you can use ok_or()?, and at some point in the nearish future, you can just use ?.
- vmarsy 8y agoI see, not very familiar with both those idioms `?` and `ok_or()?` My current understanding is that those would return an Error only? I was more describing cases where you do want to return, but not necessarily return an `Error`. For instance in a simplified example function that returns a boolean, you could decide to return `false`. is it possible there? // Function that returns a boolean value fn is_equal_to_ten(n: Option<u32>) -> bool { // some one liner that checks for None, if it's not none, gives you `x` when `n` matches content of `Some(x)` (not real code): if let Some(x) = n else { return false; /* what to do in case it's a None*/ } // `x` is available here: return (x == 10); } Would this be considered bad practice in Rust?
- lincpa 8y agoI think the concept of ownership of rust should be divided into "ownership " and "right of use " two parts. This is more in line with the "bank lending model " it advocates.