Most active commenters
  • vlovich123(9)
  • zelphirkalt(7)
  • Tuna-Fish(3)
  • throwawayffffas(3)

←back to thread

517 points bkolobara | 50 comments | | HN request time: 1.747s | source | bottom
Show context
BinaryIgor ◴[] No.45042483[source]
Don't most of the benefits just come down to using a statically typed and thus compiled language? Be it Java, Go or C++; TypeScript is trickier, because it compiles to JavaScript and inherits some issues, but it's still fine.

I know that Rust provides some additional compile-time checks because of its stricter type system, but it doesn't come for free - it's harder to learn and arguably to read

replies(17): >>45042692 #>>45043045 #>>45043105 #>>45043148 #>>45043241 #>>45043589 #>>45044559 #>>45045202 #>>45045331 #>>45046496 #>>45047159 #>>45047203 #>>45047415 #>>45048640 #>>45048825 #>>45049254 #>>45050991 #
1. pornel ◴[] No.45043105[source]
To a large extent yes, but Rust adds more dimensions to the type system: ownership, shared vs exclusive access, thread safety, mutually-exclusive fields (sum types).

Ownership/borrowing clarifies whether function arguments are given only temporarily to view during the call, or whether they're given to the function to keep and use exclusively. This ensures there won't be any surprise action at distance when the data is mutated, because it's always clear who can do that. In large programs, and when using 3rd party libraries, this is incredibly useful. Compare that to that golang, which has types for slices, but the type system has no opinion on whether data can be appended to a slice or not (what happens depends on capacity at runtime), and you can't lend a slice as a temporary read-only view (without hiding it behind an abstraction that isn't a slice type any more).

Thread safety in the type system reliably catches at compile time a class of data race errors that in other languages could be nearly impossible to find and debug, or at very least would require catching at run time under a sanitizer.

replies(4): >>45043414 #>>45043440 #>>45047837 #>>45052706 #
2. zelphirkalt ◴[] No.45043414[source]
What annoys me about borrowing is, that my default mode of operating is to not mutate things if I can avoid it, and I go to some length in avoiding it, but Rust then forces me to copy or clone, to be able to use things, that I won't mutate anyway, after passing them to another procedure. That creates a lot of mental and syntactical overhead. While in an FP language you are passing values and the assumption is already, that you will not mutate things you pass as arguments and as such there is no need to have extra stuff to do, in order to pass things and later still use them.

Basically, I don't need ownership, if I don't mutate things. It would be nice to have ownership as a concept, in case I do decide to mutate things, but it sucks to have to pay attention to it, when I don't mutate and to carry that around all the time in the code.

replies(5): >>45043496 #>>45043550 #>>45043678 #>>45044243 #>>45050174 #
3. w10-1 ◴[] No.45043440[source]
Readers would benefit from distinguishing effects systems from type systems - error handling, async code, ownership, pointers escaping, etc. are all better understood as effects because they pertain to usage of a value/type (though the usage constraints can depend on the type properties).

Similarly, Java sidesteps many of these issues in mostly using reference types, but ends up with a different classes of errors. So the C/pointer family static analysis can be quite distinct from that for JVM languages.

Swift is roughly on par with Rust wrt exclusivity and data-race safety, and is catching up on ownership.

Rust traits and macros are really a distinguishing feature, because they enable programmer-defined constraints (instead of just compiler-defined), which makes the standard library smaller.

replies(2): >>45043497 #>>45043590 #
4. arnsholt ◴[] No.45043496[source]
Ownership serves another important purpose: it determines when a value is freed.
replies(1): >>45044466 #
5. timeon ◴[] No.45043497[source]
Swift even if catching up a bit is probably not going to impose strict border between safe and unsafe.
6. timeon ◴[] No.45043550[source]
> While in an FP language you are passing values

By passing values do you mean 'moving'? Like not passing reference?

replies(1): >>45044453 #
7. ModernMech ◴[] No.45043590[source]
Swift has such a long way to go in general ergonomics of its type system, it's so far behind compared to Rust. The fact that the type checker will just churn until it times out and asks the user to refactor so that it can make progress is such a joke to me, I don't understand how they shipped that with a straight face.
replies(2): >>45044274 #>>45048511 #
8. pornel ◴[] No.45043678[source]
Borrowing isn't for mutability, but for memory management and limiting data access to a static scope. It just happens that there's an easy syntax for borrowing as shared or exclusive at the same time.

Owned objects are exclusively owned by default, but wrapping them in Rc/Arc makes them shared too.

Shared mutable state is the root of all evil. FP languages solve it by banning mutation, but Rust can flip between banning mutation or banning sharing. Mutable objects that aren't shared can't cause unexpected side effects (at least not any more than Rust's shared references).

9. vlovich123 ◴[] No.45044243[source]
It sounds like you may not actually know Rust then because non-owning borrow and ownership are directly expressible within the type system:

Non-owning non mutating borrow that doesn’t require you to clone/copy:

    fn foo(v: &SomeValue)
Transfer of ownership, no clone/copy needed, non mutating:

    fn foo(v: SomeValue)
Transfer of ownership, foo can mutate:

    fn foo(mut v: SomeValue)

AFAIK rust already supports all the different expressivity you’re asking for. But if you need two things to maintain ownership over a value, then you have to clone by definition, wrapping in Rc/Arc as needed if you want a single version of the underlying value. You may need to do more syntax juggling than with F# (I don’t know the language so I can’t speak to it) but that’s a tradeoff of being a system engineering language and targeting a completely different spot on the perf target.
replies(2): >>45044516 #>>45049874 #
10. vlovich123 ◴[] No.45044274{3}[source]
If you solve 80% of the problems by spending 20% of the time, is it worth spending the 80% to solve 20% of the problems? Or even if it is, is it more valuable to ship the 80% complete solution first to get it into the hands of users while you work on the thornier version?
replies(1): >>45045674 #
11. zelphirkalt ◴[] No.45044453{3}[source]
Yes, I guess in Rust terms, that is called moving. However, when I have some code that "moves" the value into another procedure, then the code after that call, can no longer use the moved value.

So I want to move a value, but also be able to use it after moving it, because I don't mutate it in that other function, where it got moved to. So it is actually more like copying, but without making a copy in memory.

It would be good, if Rust realized, that I don't have mutating calls anywhere and just lets me use the value. When I have a mutation going on, then of course the compiler should throw error, because that would be unsafe business.

replies(2): >>45044767 #>>45045055 #
12. zelphirkalt ◴[] No.45044466{3}[source]
I guess it is then a necessary complication of the language, as it doesn't have garbage collection, and as such doesn't notice, when values go out of scope of all closures that reference them?
replies(2): >>45045566 #>>45051647 #
13. zelphirkalt ◴[] No.45044516{3}[source]
Can you give examples of the calls for these procedures? Because in my experience when I pass a value (not a reference), then I must borrow the value and cannot use it later in the calling procedure. Passing a reference of course is something different. That comes with its own additional syntax that is needed for when you want to do something with the thing that is referred to.
replies(2): >>45044985 #>>45045709 #
14. asa400 ◴[] No.45044767{4}[source]
I'm not sure how what you're describing is different from passing an immutable/shared reference.

If you call `foo(&value)` then `value` remains available in your calling scope after `foo` returns. If you don't mutate `value` in foo, and foo doesn't do anything other than derive a new value from `value`, then it sounds like a shared reference works for what you're describing?

Rust makes you be explicit as to whether you want to lend out the value or give the value away, which is a design decision, and Rust chooses that the bare syntax `value` is for moving and the `&value` syntax is for borrowing. Perhaps you're arguing that a shared immutable borrow should be the default syntax.

Apologies if I'm misunderstanding!

15. Tuna-Fish ◴[] No.45044985{4}[source]
> Because in my experience when I pass a value (not a reference), then I must borrow the value and cannot use it later in the calling procedure.

Ah, you are confused on terminology. Borrowing is a thing that only happens when you make references. What you are doing when you pass a non-copy value is moving it.

Generally, anything that is not copy you pass to a function should be a (non-mut) reference unless it's specifically needed to be something else. This allows you to borrow it in the callee, which means the caller gets it back after the call. That's the workflow that the type system works best with, thanks to autoref having all your functions use borrowed values is the most convenient way to write code.

Note that when you pass a value type to a function, in Rust that is always a copy. For non-copy types, that just means move semantics meaning you also must stop using it at the call site. You should not deal with this in general by calling clone on everything, but instead should derive copy on the types for which it makes sense (small, value semantics), and use borrowed references for the rest.

replies(1): >>45045312 #
16. NIckGeek ◴[] No.45045055{4}[source]
Couldn't you just pass a reference to your value (i.e. `&T`)? If you absolutely _need_ ownership the function you call could return back the owned value or you could use one of the mechanisms for shared ownership like `Rc<T>`. In a GC'd functional language, you're effectively getting the latter (although usually a different form of GC instead of reference counting)
replies(1): >>45045332 #
17. zelphirkalt ◴[] No.45045312{5}[source]
It is not possible then to pass a value (not a reference) and not implement or derive Copy or Clone, if I understand you correctly. That was my impression earlier. Other languages let you pass a value, and I just don't mutate that, if I can help it. I usually don't want to pass a reference, as that involves syntactical "work" when wanting to use the referenced thing in the callee. In many other languages I get that at no syntactical cost. I pass the thing by its name and I can use it in the callee and in the caller after the call.

What I would prefer is, that Rust only cares about whether I use it in the caller after the call, if I pass a mutable value, because in that case, of course it could be unsafe, if the callee mutates it.

Sometimes Copy cannot be derived and then one needs to implement it or Clone. A few months ago I used Rust again for a short duration, and I had that case. If I recall correctly it was some Serde struct and Copy could not be derived, because the struct had a String or &str inside it. That should a be fairly common case.

replies(4): >>45045542 #>>45045712 #>>45045719 #>>45046488 #
18. zelphirkalt ◴[] No.45045332{5}[source]
I think I could. But then I would need to put & in front of every argument in every procedure definition and also deal with working with references inside the procedure, with the syntax that brings along.
replies(2): >>45045629 #>>45047259 #
19. steveklabnik ◴[] No.45045542{6}[source]
Yes, Rust will not automatically turn a value into a reference for you. A reference is the semantic you desire. If you have a value, you’re gonna have to toss & on it. That’s the idiomatic way to do this, not to pass a value and clone it.

&str is Copy, String is not.

20. steveklabnik ◴[] No.45045566{4}[source]
Yes, but it’s more subtle than that. What Rust does is track when the object goes out of scope, and will make sure that any closures that reference it live for a shorter time than that. Sort of backwards of what you’re asking.
21. Mond_ ◴[] No.45045629{6}[source]
Fair to be annoyed by this, but not very interesting: This is just a minor syntactical pattern that exists for a very good reason.

Syntax is generally the least interesting/important part of languages.

22. Mond_ ◴[] No.45045674{4}[source]
If someone else ships a 100% solution, or a solution that doesn't have the problems your potentially half-baked "80% solution" does, then you might be in trouble.

There's a fine line here: it matters a lot whether we're talking about a "sloppy" 80% solution that later causes problems and is incredibly hard to fix, or if it's a clean minimal subset, which restricts you (by being the minimal thing everyone agrees on) but doesn't have any serious design flaws.

replies(1): >>45045823 #
23. vlovich123 ◴[] No.45045709{4}[source]
If all you're doing is immutable access, you are perfectly free to immutably borrow the value as many times as you want (even in a multithreaded environment provided T is Send):

    let v = SomeValue { ... }
    foo(&v);
    foo(&v);
    eprintln!("{}", v.xyz);
You have to take a reference. I'm not sure how you'd like to represent "I pass a non-reference value to a function but still retain ownership without copying" - like what if foo stored the value somewhere? Without a clone/copy to give an isolated instance, you've potentially now got two owners - foo and the caller of foo which isn't legal as ownership is strictly unique. If F# lets you do this, it's likely only because it's generating an implicit copy for you (which Rust is will do transparently for you when you declare your type inheriting Copy).

But otherwise I'm not clear what ownership semantics you're trying to express - would be helpful if you could give an example.

24. Tuna-Fish ◴[] No.45045712{6}[source]
You can pass a value that is neither copy or clone, but then it gets moved into the callee, and is no longer available in the caller.

Note that calling by value is expensive for large types. What those other languages do is just always call by reference, which you seem to confuse for calling by value.

Rust can certainly not do what you would prefer. In order to typecheck a function, Rust only needs the code of that function, and the type defitions of everything else, the contents of the functions don't matter. This is a very good rule, which makes code much easier to read.

replies(1): >>45062978 #
25. vlovich123 ◴[] No.45045719{6}[source]
> Other languages let you pass a value, and I just don't mutate that, if I can help it

How do they do that without either taking a reference or copying/cloning automatically for you? Would be helpful if you provide an example.

replies(1): >>45046876 #
26. vlovich123 ◴[] No.45045823{5}[source]
Sure. And I'm not sure the type checker failing on certain corner cases and asking you to alter the code to be friendlier is a huge roadblock if it rarely comes up in practice for the vast majority of developers.
27. theLiminator ◴[] No.45046488{6}[source]
The pattern you're looking for is:

``` fn operate_on_a(a: A) -> A { // do whatever as long as this scope still owns A a } ```

28. zelphirkalt ◴[] No.45046876{7}[source]
I did not state, that they don't automatically copy or clone things.

I might be wrong what they actually do though. It seems I merely dislike the need to specify & for arguments and then having to deal with the fact, that inside procedures I cannot treat them as values, but need to stay aware, that they are merely references.

replies(1): >>45047653 #
29. pepa65 ◴[] No.45047259{6}[source]
When you pass &variable, I don't think it affects the syntax inside the called function, does it?
replies(1): >>45047610 #
30. asa400 ◴[] No.45047610{7}[source]
Correct. If you then want to subsequently re-reference or dereference that reference (this happens sometimes), you'll need to accordingly `&` or `*` it, but if you're just using it as is, the bare syntactical `name` (whatever it happens to be) already refers to a reference.
replies(1): >>45053161 #
31. const_cast ◴[] No.45047653{8}[source]
C++ auto copies as well, it's just a feature of value semantics. References must be taken manually - versus Java or C#, where we assume reference and then have to explicitly say copy. Rust, I believe, usually moves by default - not copy, but close - for most types.

The nice thing about value semantics is they are very safe and can be very performant. Like in PHP, if we take array that's a copy. But not really - it's secretly COW under the hood. So it's actually very fast if we don't mutate, but we get the safety of value semantics anyway.

replies(1): >>45053644 #
32. bpicolo ◴[] No.45047837[source]
I think tagged unions with exhaustive type checking and no nulls are the two killer features for correctness
33. zozbot234 ◴[] No.45048511{3}[source]
There's nothing wrong with this in principle, every type system must reject some valid programs. There's no such thing as a "100%" type system that will both accept all valid code and reject all non-valid code.
replies(1): >>45048621 #
34. ModernMech ◴[] No.45048621{4}[source]
I'm not questioning the principle, I'm critiquing the implementation versus the competition. Swift doesn't do a good job, it throws up its hands too often.
35. throwawayffffas ◴[] No.45049874{3}[source]
I share the same pet peeve, it's not that it's not possible. It's that I would prefer copy and or move to be the default when assigning stuff. Kind of like the experience you get using STL stuff in c++.
replies(1): >>45050608 #
36. pjmlp ◴[] No.45050174[source]
Depends on the FP language though, they are only values in the logic sense, they can be reference as well, hence the various ways to do equality.
37. vlovich123 ◴[] No.45050608{4}[source]
Copy can’t be for types that aren’t copyable because there could be huge performance cliffs hiding (eg copying a huge vector which is the default in c++).

But Rust always moves by default when assigning so I’m not sure what your complaint is. If the type declares it implements Copy then Rust will automatically copy it on assignment if there’s conflicting ownership.

replies(1): >>45058180 #
38. pclmulqdq ◴[] No.45051647{4}[source]
The borrow checker is a compile-time garbage collector. If you think about it in that sense, you can understand a lot of the ways it restricts you.
39. mason_mpls ◴[] No.45052706[source]
Apologies for the non sequitur

Do you think Zig is a valid challenger to Rust for this kind of programming?

replies(1): >>45053217 #
40. gf000 ◴[] No.45053161{8}[source]
Also, Rust does implicit dereferencing, so it's not that much of an issue in practice.
41. NobodyNada ◴[] No.45053217[source]
Zig's trying to be a "nicer C" that's easy to learn and fast to compile. It's a great language with a lot of neat design, and definitely setting itself up to be a "valid challenger" in a lot of the systems-y, performance-focused domains Rust targets. But it's not trying to compete with Rust on the safety/program correctness front.

Almost none of the Rust features discussed in this subthread are present in Zig, such as ownership, borrowing, shared vs. exclusive access, lifetimes, traits, RAII, or statically checked thread safety.

replies(1): >>45053699 #
42. vlovich123 ◴[] No.45053644{9}[source]
Rust will transparently copy values for types that declare the Copy trait. But the default is move which is probably what C++ would have chosen had they had the 30+ years of language research to experiment with that Rust did + some other language to observe what worked and what didn't.
43. mason_mpls ◴[] No.45053699{3}[source]
Thank you
44. throwawayffffas ◴[] No.45058180{5}[source]
I have been thinking about how to express it.

My complaint is that because moves are the default, member access and container element access typically involves borrowing, and I don't like dealing with borrowed stuff.

It's a personal preference thing, I would prefer that all types were copy and only types marked as such were not.

I get why the rust devs went the other way and it makes sense given their priorities. But I don't share them.

Ps: most of the time I write python where references are the default but since I don't have to worry about lifetimes, the borrow checker, or leaks. I am much happier with that default.

replies(1): >>45065140 #
45. akkad33 ◴[] No.45062978{7}[source]
Is it expensive in Rust? Normally only data in stack gets copied. Heap data is untouched
replies(1): >>45065163 #
46. vlovich123 ◴[] No.45065140{6}[source]
You're not talking about copying values. You want it to be easy to have smart references and copy them around like you do in Python and Java, but it's more complicated in Rust because it doesn't have a GC like Python and Java.

In Rust, "Copy" means that the compiler is safe to bitwise copy the value. That's not safe for something like String / Vec / Rc / Arc etc where copying the bits doesn't copy the underlying value (e.g. if you did that to String you'd get a memory safety violation with two distinct owned Strings pointing to the same underlying buffer).

It could be interesting if there were an "AutoClone" trait that acted similarly to Copy where the compiler knew to inject .clone when it needed to do so to make ownership work. That's probably unlikely because then you could have something implement AutoClone that then contains a huge Vector or huge String and take forever to clone; this would make it difficult to use Rust in a systems programming context (e.g. OS kernel) which is the primary focus for Rust.

BTW, in general Rust doesn't have memory leaks. If you want to not worry about lifetimes or the borrow checker, you would just wrap everything in Arc<Mutex<T>> (when you need the reference accessed by multiple threads) / Rc<RefCell<T>> (single thread). You could have your own type that does so and offers convenient Deref / DerefMut access so you don't have to borrow/lock every time at the expense of being slower than well-written Rust) and still have Python-like thread-safety issues (the object will be internally consistent but if you did something like r.x = 5; r.y = 6 you could observe x=5/y=old value or x=5/y=6). But you will have to clone explicitly the reference every time you need a unique ownership.

replies(1): >>45069251 #
47. Tuna-Fish ◴[] No.45065163{8}[source]
Yes, but if you have a large value type it will be on the stack unless you manually box it. Passing by value can get quite expensive quite fast, especially if the value keeps being passed up and down the call chain.
replies(1): >>45084828 #
48. throwawayffffas ◴[] No.45069251{7}[source]
No, I fully understand the difference. I am just saying since I don't have a GC, I would rather have the system do copies instead of dealing with references.

At least as long as I can afford it performance wise. Then borrowing it is. But I would prefer the default semantics to be copying.

replies(1): >>45070211 #
49. vlovich123 ◴[] No.45070211{8}[source]
> At least as long as I can afford it performance wise. Then borrowing it is. But I would prefer the default semantics to be copying.

How could/would the language know when you can and can't afford it? Default semantics can't be "copying" because in Rust copying means something very explicit that in C++ would map to `is_trivially_copyable`. The default can't be that because Rust isn't trying to position as an alternative for scripting languages (even though in practice it does appear to be happening) - it's remarkable that people accept C++'s "clone everything by default" approach but I suspect that's more around legacy & people learning to kind of make it work. BTW in C++ you have references everywhere, it just doesn't force you to be explicit (i.e. void foo(const Foo&) and void foo(Foo) and void foo(Foo&) all accepts an instance of Foo at the call site even though very different things happen).

But basically you're argument boils down to "I'd like Rust without the parts that make it Rust" and I'm not sure how to square that circle.

50. akkad33 ◴[] No.45084828{9}[source]
Is this really true? What do you mean by value types? The types that implement copy or any struct types? Because I think struct types only get moved