Rust 1.49.0(blog.rust-lang.org) |
Rust 1.49.0(blog.rust-lang.org) |
Last time I tried getting into Rust, some years ago, the recommended way to install it was to use the rustup tool. You were also kind of expected to learn using the "nightly" version of the language, because much of the documentation and stackoverflow answers depended on that.
Is this still the case now that we're about to enter 2021? Is it OK to learn rust by installing it via "apt install", or is it still recommended to use rustup? Is it OK to stick just to stable Rust or should I expect that I will need to install the nightly version at some point?
All the stuff I did worked fine - 3D graphics with OpenGL and SDL2, web services with Hyper and Tokio (recently hit 1.0!), and CLI apps.
If you want to try apt install first, you can do that - It's easy to remove. But personally I do use rustup.
Rust has a 6 week release cadence, and while the language has settled down significantly over the last 1-2 years, there are still a lot of new features arriving that library maintainers are eager to use. Combined with performance improvements, you will almost always want to use a recent compiler.
Relatively slow moving package repositories are not a great fit for that reason. Rustup also handles installing support for various architectures - which are often not packaged well - and fast-moving tools like rust-analyzer.
The nightly situation has gotten much, much better though. Almost non of the popular crates still require nightly, and staying on stable is just fine for most projects.
Not every distribution is Debian Stable.
Re: apt install - I never trust the OS packages for anything like developer tools, I'd rather have everything run out of my home directory. Then again, I'm not a C/C++ developer where the OS, libraries, build tools are all intertwined.
https://blog.rust-lang.org/2020/12/16/rust-survey-2020.html
> the number of users who are relying on a nightly compiler at least part of the time continues to drop - down to 28% compared with last year’s 30.5% with only 8.7% of respondents saying they use nightly exclusively. When asked why people are using nightly the largest reason was to use the Rocket web framework which has announced it will work on the stable version of Rust in its next release. The next largest reason for nightly was const generics, but with a minimal version of const generics reaching stable, we should see less of a reliance on nightly for this feature.
TL;DR: unless you're doing certain specific things, stable Rust should work well for you.
Regarding rustup vs apt, you can absolutely install via apt if you want to. Depending on what version you get, you may or may not be far enough behind the rest of the world for it to be a pain. Which version you'll get depends on the specifics of the distro.
I think it's still recommended to use rustup.
I know Rust is community driven, so it's not like contributions will appear from thin air. But I guess maybe it would be time to promote/incentivize people to contribute support for microcontrollers. This is a realm where C reigns and Rust would be a bowl of fresh air.
Last time I checked (6 month ago), the Rust AVR fork had just been merged upstream. This removed the necessity to build a forked rustc from a patched llvm.
I would have to re-check recent updates, but at the time there were still a lot of bugs, no core libs, etc.
That's not what I would call "full support".
I mean, Rust does have support for many microcontrollers. I do ARM stuff for work, for example. Just not AVR. It'll be nice to have it though!
For me it was specially nice to have some minutes shaved off from full builds.
(Yes, I know that "unstable" in slice::select_nth_unstable refers to unstable sorting.)
Being able to guarantee that they pass means having the expertise to fix any issues, and with a timeliness to be able to fix them and not block a release. That requires people around to support the target, with a higher burden than tier 2.
(Technically, it's even more than "not block a release" it's "not block any PR that may start failing on that target," since all tests must pass before a PR is landed.)
You could ask: why aren't the tier 2 tests just run before release? But then, if they are broken it may be a significant amount of work to fix, and could delay the release.
Maybe there is a middle-ground where tier 2 tests are run daily, but then you need a team of people just to fix those tests, because it will no longer be on the original PR author to make sure those tests pass before their PR is merged.
This issue though prevents me from recommending Rust for closed source development to my colleagues: https://github.com/rust-lang/rust/issues/40552
[0] https://www.reddit.com/r/adventofcode/comments/kj53l1/unoffi...
- Jetbrains IDE with the Rust plugin (maintained by Jetbrains itself). The free IntelliJ IDE Community works really well. CLion or IntelliJ Ultimate are necessary for debugging support
- The Rust-analyser tool. A language server that can be used, in theory, on any IDE supporting the LSP protocol. Code is the most used IDE with this tool since it is the reference IDE of the project.
Rust is nice language btw.
But,when will stable version of Rust be released? By stable,i mean, number of new features added must not be too much. Rust currently seem to be adding too many features every release (which is nice but also not so good at same time)
What is "too much"? How many would you prefer? How does this release have too many features? This release has three, and they're all pretty small. Some could even argue that they may not even count as new features, but remove restrictions between combinations of existing features.
Have you seen how many new features have been added to C++20? (which is probably the closest language to Rust) Not to mention any of the dynamically typed languages.
match result {
Ok(value) => value,
Err(result) => {
panic!("error traversing directories {}", result);
}
};
It's awkward and ugly. I'm back to C#, now on .NET 5.) and find that it just got noticeably faster! It was already fast."Astonishing Performance of .NET 5: More Data"
https://medium.com/swlh/astonishing-performance-of-net-5-mor...
This is entirely up to you; unless you find method calls ugly, in which case, you've got bigger problems :)
> They need to take more inspiration from C#
Could you elaborate a bit? I'm not familiar with what C# does here.
And I just wish generic type parameters wouldn't have to be propagated through all types touching them.
That said I'm really happy with how it develops and Rust comes with many little details that I sorely miss in other languages. Thanks for all the effort.
I'm still figuring my way around rust so obviously some noob questions follow: -> what's with the move/copy mess ? I know why they are needed but it seem to be in the face with all the explicit '&' all over the place in any reasonably sized code. Why not hide it a bit by letting the implicit copy to happen to simpler structures ? (at compile time).
-> Why no love for inheritance? :) - it makes certain patterns easier to implement
-> Why no love for global/static variables ? I know they are prone to be misused but some patterns like singleton really need a lot of shortcuts to implement. And there will always be some cases where you want to keep variables with static and global scope
* Into, with s.into()
* An inherent method, .as_str()
* Deref coercion, &s
* Reborrowing, &*s (this builds on Deref too but isn't a coercion and can be done in places where coercion doesn't kick in)
... and probably some others I'm forgetting.
result.unwrap_or_else(|e| panic!("error traversing directories {}", e));
There are a lot of methods on various types to reduce this kind of thing. If you didn't want to interpolate the value of e, it would be even simpler: result.expect("error traversing directories");For those reading along (not Steve) expect does do that, but using the Debug formatter instead of Display, as the grandparent used.
IMO the_duke summarized it perfectly in other comment: You are essentially complaining that Rust is not C#; Rust is much lower level and makes very different tradeoffs; most of the design decisions are there for a reason, and are good choices (https://news.ycombinator.com/item?id=25593825)
People considering Rust as an alternative for higher-level programming languages are in for a potential surprise or two. I guess this happens because Rust has received a lot of attention and promotion, enough to make some people consider it, where otherwise they wouldn't have thought of using tools that stand at a lower level than what is most appropriate for their needs (or knowledge).
EDIT: I've now read that in this particular case, the parent commenter is consciously playing with different languages to learn about them. Still, I think it would be a misconception to think that C# and Rust are at an equivalent level of programming abstraction, and thus should offer similar ergonomics.
You still have languages that can't (really) even do async/threaded computation (Python, PHP, JavaScript/Node can't do threads AFAIK).
I've said this before: "Rust is the highest level low level language I've ever used. Java is the lowest level high level language I've ever used."
enum Result<T, E> {
Ok(T),
Err(E),
}
match header.get(0) {
None => Err("invalid header length"),
Some(&1) => Ok(Version::Version1),
Some(&2) => Ok(Version::Version2),
Some(_) => Err("invalid version"),
}
I wasn't saying it was bad, just a pain point for me.Jokes aside there are many helper methods on `Result` to make it more Rustic, try looking into: https://doc.rust-lang.org/std/result/enum.Result.html
As a library maintainer I need to make the choice of which version to target.
It's easy to accidently use features of a recent rust version, as you can see in this example:
https://github.com/mkmik/slyce/issues/17
I could work around this issue and pin the rustc version in the CI system to avoid regressions, but is it worth the effort since it's likely that this particular user will eventually depend on another library that uses a feature of >1.43 and thus eventually give in and use rustup? I want to be helpful towards users of my library, but I wonder if the most rational choice is to encourage users to upgrade the toolchain more liberally.
This has the funny effect of posts getting harder to write as time goes on; we have less releases with big, important features, and more releases with "tons of bugfixes and some minor improvements."
Possibly write about the reasons something was changed and the use cases improved, instead of the changes themselves?
I do try to write about the reasons why and use-cases improved. One of the issues is that that increases the amount of text, which directly goes against the idea of quickly finding what you want.
At the end of the day, if you want to know everything, you have to read everything. There's no shortcuts. I try to highlight the best things that the most people will want to know about, but if you really want to know everything, there's no better way than going straight to the source, like I do to create the post in the first place.
Regardless, I don't think the cost/benefit is right here; the posts and notes are already pretty short, and should only take a few minutes to read, even if you read all of them.
I think the downvotes are because both the example and the generalized statement that C# is "noticeably faster" is bait / lazy.
Ah gotcha - my mistake :)
If you're familiar with say, `Vec<u8>` and `[u8]`, `String` and `str` are basically the same except they are contractually valid UTF bytes. So just like you can `push` and `extend` to a `Vec`, you can do the same to a `String`.
With regard to generic type parameters, if you want to code in Java or Go style, you can use dynamic dispatch trait objects to remove type parameters.
I've found that sometimes this doesn't happen automatically (at least when passing as an argument; maybe not when calling methods). i.e., you have to explicitly call .as_str() in some situations. Even as someone who's comfortable with the String/&str distinction and moderately familiar with Rust, it's not clear to me where this is and isn't necessary. The compiler just tells me when I make the wrong guess.
Any time you have a &String reference, it triggers coercion to &str.
The other ways are more "advanced", for when you're dealing with (for example) potentially unsafe coercions or you don't want to rely on inference for some reason.
Would have been easier to implement with a copy constructor I guess. Why not implicitly clone in some cases (since classes like String gets used so frequently).
Automatically copying strings may not be a great idea: https://news.ycombinator.com/item?id=8704318
Because they get used so frequently. Why would we want to add expensive clones to frequently used operations?
This would be like asking why LINQ methods in C# aren't deferred by default. Yes, there's a few situations where that would be nice but it would make the functions largely useless because of how poor performance would be.
I was imagining something spatial, a drawing, a map, something that makes it possible to overview and place the new features in context with each other. Probably nothing that can be realized.
Rust is much lower level and makes very different tradeoffs. Sometimes for the sake of performance, sometimes to enhance code readability.
But most of the design decisions are there for a reason, and are good choices.
Simple types (that are small and can be trivially memcopied) can implement the `Copy` trait, which makes cloning transparent. For other types, the `Clone` trait is there with `.clone()`. Having expensive copies be explicit is a intentional design decision.
For value conversions, the `Into/From` and `TryInto/TryFrom` traits make conversions a (usually type inferred) function call (.into(), .try_into()), which is really quite convenient, though at the expense of readability.
Regarding strings: they are are definitely complicated and sometimes awkward in Rust. But I'd argue that strings are inherently complicated. Most languages hide this complexity by just allocating and doing everything on the heap, which is not great in a language that values performance and wants to support environments without allocators.
Examples:
Convert.ToInt32(String) – This is _parsing_. In Rust, use `parse`.
Convert.ToString(Int32) – This is _stringifying_. In Rust, use `to_string`.
Convert.ToInt64(Int32) – This is an _infallible conversion_. In Rust, use `into`.
Convert.ToInt32(Int64) – This is a _fallible conversion_. In Rust, use `try_into`.
In all these cases, Rust gives you more immediate semantic information about the conversion, and in fewer characters too!
This is already the case. Built-in types that are simple enough to be copied implicitly already are (roughly: those which don't manage any memory or other resources), and you can enable this for your own types with `#[derive(Copy)]`, as long as they are composed only of implicitly copyable types.
#[derive(Copy)]
struct S {
x: i32,
y: usize,
z: Option<Result<(), ()>>,
}
fn f(x: S) {
// ...
}
fn main() {
let s = S { x: 0, y: 0, z: Some(Ok(())) };
f(s);
f(s);
}
Something like `String` isn't implicitly copyable in Rust, because it manages memory, and therefore copying it would require a heap allocation.The Rust way of forcing non-trivial clones to be explicit is much better than C++ IMO, where someone forgetting a `&` or an `std::move` somewhere can cause an innocuous-looking function call to be arbitrarily slow.
In C# there are not implicit copies either (except of value types), because more complex types in C# are accessed via pointers to garbage-collected heap objects. Rust doesn't have a garbage collector, though.
Rust doesn't deal with "prone to misuse" but "provably safe, else explicitly unsafe, or made safe by the programmer through wrapping code." Global variables are inherently unsafe and need to be wrapped as such.
Of course you'll need global state at some point in your life. What Rust does is yell to remind you that it isn't thread safe.
If you stop thinking about a Rust program as a script where the runtime figures the hard stuff out for you, then these design decisions make a lot more sense. You have a lot more knobs to twiddle than in C#, no garbage collector, and no runtime. The compiler is pretty smart, but it tells you the things it knows and you're responsible for working around the limitations to create sound programs that the compiler can optimize.
> Why not hide it a bit by letting the implicit copy to happen to simpler structures ?
This is the Copy trait.
> Why no love for inheritance
There are a variety of reasons, but one interesting one is that inheritance and strong type inference have issues, and we have very strong type inference. Beyond that, there are various other reasons, but what it really comes down to is that there's just not a ton of pressure to actually implement it; it's not enough of an impediment for Rust users to justify adding it. Most requests come from people who do not write Rust, and once people get into Rust and how it works, they don't seem to need it much anymore.
This is of course very general and there are some people who love it and want it badly anyway, but "some people exist who want this feature" is not enough to make it happen. Rust already has a lot of features, and some people say too many. We have to be careful here.
> Why no love for global/static variables ?
What does "love" mean? Rust absolutely supports these.
So there's a lot to unpack here, but implicit copies do happen - if it's a copy-able data structure. Strings are huge, so no implicit copy. As far as `&` being too much to identify references vs not, i'm not sure how it could be made any shorter to identify a reference. You're already, commonly, hiding the lifetime associated with that, so it's really `&'a str`, but Rust lets you drop the `'a` most of the time.
Considerable effort has been put into easing the language and lowering syntax. What's left is essentials imo. I _want_ to see when something is a reference. I _want_ to know generic types. etcetc.
> -> Why no love for inheritance? :) - it makes certain patterns easier to implement
I can't speak much here. I've been using Go and Rust for so long i've forgotten what classical inheritance is actually useful for haha. The Go/Rust pattern of Structs, shared behavior, etc cover all use cases for me. i don't find myself missing something, fwiw, but i can't speak to which is "best".
> -> Why no love for global/static variables ? I know they are prone to be misused but some patterns like singleton really need a lot of shortcuts to implement. And there will always be some cases where you want to keep variables with static and global scope
You can have global variables fwiw. Granted, i use `lazy_static` which simplifies it a bit, but there's nothing i'm aware of which prevents this pattern. I've typically just used it in tests though. Globals are the devils candy ;)
let foo1: String = "bar".into();
let foo2 = core::convert::Into::into::<String>("bar");First of all, I find that many people aren't using multiple threads, and therefore, what they want is a thread-local, not a static. For that, you can use https://doc.rust-lang.org/stable/std/macro.thread_local.html
If you do need a static, then there are libraries like https://docs.rs/lazy_static/1.4.0/lazy_static/ and https://crates.io/crates/once_cell to help too. We have talked about adding something like this to the standard library, but it hasn't landed yet. https://github.com/rust-lang/rust/issues/74465 is the tracking issue for when it does. The reason that we don't have this yet is that it is not super urgent, given that the libraries already exist.
Now, both of those give you immutable statics, but that's where interior mutability comes in. As you can see from the thread_local examples, you can use a RefCell there, and if your type is simple enough, maybe even regular Cell. For lazy_static or once_cell, you may want to use Mutex<T>, or RwLock<T>, or some other type. For simple integers, the various Atomic* types might be better, for example. The reason this isn't built in is exactly because there are so many options; people need all of these specifics, so we have to provide them, so there's no single built-in thing.
#[macro_use]
extern crate lazy_static;
use std::sync::Mutex;
lazy_static! {
static ref ARRAY: Mutex<Vec<u8>> = Mutex::new(vec![]);
}
fn do_a_call() {
ARRAY.lock().unwrap().push(1);
}
fn main() {
do_a_call();
do_a_call();
do_a_call();
println!("called {}", ARRAY.lock().unwrap().len());
}
I agree that this isn't the most ergonomic, but like most unergonomic things in Rust, there are reasons for it being so. let my_str = "Hello".to_owned();
match &my_str {
"Hello" => (),
_ => ()
}