Arrays in for loops


#1

image

So I have an array which has no values, through a for loop I want to put the current value of x into the all the indexes of the array.

image

How come the error red underline disappears after I type this in?

And how do I exactly convert x from usize to i32?


#2

You have to initialize you array first:

let mut array = [0i32; 10];
for x in 0..array.len() {
    array[x] = x as usize;
}

But considering your dynamicly typed language experience, probably you’ll find using Vec more convinient:

let mut foo: Vec<i32> = Vec::new();
// you can define range over `i32`
for x in 0..10i32 {
    foo.push(x);
}

Note that an alternative way to create Vec is vec! macro.


#3

How come you have got this random 0 before the i32 word mate?

I have no idea what this even is, I haven’t even learn’t this yet :confused:


#4

[i32; 10] is a type, an array which stores 10 i32 elements. [0i32; 10] is array of type [i32; 10] which stores 10 zeros.

I would strongly recommend to read the book first. Otherwise it will be quite hard for you coming from dynamically typed languages, as you’ll have to think a bit differently. Here is docs for Vec, you can think about it as equivalent of Python lists.


#5

I’d definitely recommend reading the Rust book if you haven’t already - it’ll introduce concepts to you in an order that makes sense.


#6

How are Rust methods an advantage over dynamically typed languages?


#7

Thanks mate :slight_smile:


#8

I wouldn’t say that it is a pure advantage, it is more of a different compromise.

Putting more constraints on types makes interfaces easier to understand (because well-designed types can be used to explain what input/output is acceptable and what isn’t), allows more automatic program correctness checking (ideally at compile-time and in a general fashion), and enables more optimization (the more the compiler knows about your goals, the more it can optimize towards them).

The price to pay is that programming becomes a less spontaneous exercise: the compiler expends less effort at figuring out what you mean, and you spend more energy explaining yourself in detail.

As a result, dynamic typing is usually considered better for quick throw-away code (competitions, prototypes), where the goal is to get from nothing to mostly working in as little time as possible, whereas static typing is usually considered better for large long-lived codebases that have stronger pressure to be correct.


#9

Rust helps you to write more reliable code with a much better performance, than you can achieve in languages like Python (e.g. see benchmark game results), but in return you’ll have to spend a bit more time writing code and think much harder about what exactly your code should do.


#10

If you want to go down the rabbit hole you could even do something like this:

(0..10).collect::<Vec<i32>>()


#11

https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/gcc-rust.html

I compared C with Rust and how come C seems to be the winner in these benchmarks?


#12

Yes (though mind that C can be bitten with hand written and carefully designed assembly), but Rust provides higher levels abstractions (which unfortunately not always can be optimized out) and much-much more safety and reliability compared to what you’ll get in C. Plus GCC is usually somewhat better than LLVM at optimizations.


#13

What if people didn’t chose to use higher level abstractions, then is it possible to generate just as fast code as C code?

Also is C faster than Rust cause of how Mozilla has not figured out how to make a compiler than can optimize code very well at this time?


#14

It’s not reasonable to say that language X “is faster” than language Y. That’s a huge sweeping generalization that ignores most of the reasons performance is difficult and volatile in practice. A random code snippet written in both C and Rust might be faster in either language, and in the typical case which one “wins” has more to do dumb luck or the experience of the programmer writing them than anything to do with the languages. Which language is “winning” on a benchmarking site like that is largely about who wrote the programs being benchmarked and how much time they put into optimizing them (iirc people actually have updated these programs multiple times to make Rust and its “competitors” faster, so who’s #1 keeps changing).

In principle, “Rust is just as fast as C” in the sense that you should be able to get any program running just as fast in Rust as you could in C, because Rust has no runtime and its abstractions are zero-overhead whenever possible. There are also many cases where, in principle, Rust is faster than C because of its stricter type system (e.g. it knows &mut cannot be aliased) and because it provides more zero-overhead abstractions (e.g. generics are often faster at runtime than passing function pointers; this is why C++'s std::sort is famously faster than C’s qsort()).

In practice, rustc is using the same LLVM backend that clang does, so Rust has always gotten most of the same non-trivial optimizations that C and C++ do. So afaik the only cases where C outperforms Rust today because it’s C (rather than because of a rustc or LLVM bug, or because the programmer knew C better) are simply missing features in Rust, like inline assembly, SIMD, alloca, etc. And all of those features are coming.


#15

Just compare the runtime of code compiled without --release and with --release and you’ll know how good an optimizing compiler “Mozilla” (actually LLVM) have made. (It’s the same backend as for the Clang C compiler.)

There’s no reason why Rust should generally be faster than handcrafted C. But there is a lot of reasons why it should be less bug-prone, therefore safer, while being quicker to get right the first time.


#16

Even C++ loses to C in those tests. Does that mean there is no merit to C++ either?


#17

Fair enough mate you do make a good point.

However with this phrase I would like to point out that if you were to compare a compiled language with a non - compiled language for example C++ vs Java, C++ can easily beat Java in performances as you know Java has to use a virtual machine in order to convert the intermediate code into machine code on the fly during run time.


#18

Oh


#19

This is true (although Java is compiled, to java bytecode, just to be pedantic).

However C, C++, and Rust all compile to the same flavours of assembly language - this is why the comparison is not meaningful. Python and Java have overheads in their virtual machines, but Rust and C (ideally) do not have any overhead. They are deliberately compiled to try to minimize any extra work.

If you want your code to be the fastest possible, there is some theoretical best sequence of assembly instructions to accomplish that. C and Rust (again, at least in theory) are both capable of generating this. It’s not ever going to be clear-cut which one will happen to do the better job.

If you were ever so concerned with speed that you had to pick the fastest language for your use case between Rust and C, it’s very likely that you would be better off hand-writing the assembly yourself. In practice, this is not going to happen. Either language will be fast enough.


#20

Even in a case like C++ vs Java it’s not quite that simple. Theoretically, VM languages can beat “native” code in some cases because, unlike an ahead-of-time compiler, the VM and its just-in-time compiler have the luxury of knowing the exact machine they’re running on. It’s also quite common in practice for programs in VM languages to have runtime performance close to and sometimes even negligibly different from the corresponding native program (though the VM will typically use a lot more memory than the corresponding native program to pull that off).

What really distinguishes C++ from Java/Python/etc is that C++'s performance is more deterministic and consistent by default, and it gives you a lot more control over performance for when the defaults aren’t good enough. Rust should give you just as much determinism as C or C++ today, and likewise for control once all the missing features get filled in.


Assuming that by “Rust methods” you mean “statically typed methods”, performance is the obvious reason that most of these replies have been focusing on, but static typing is also about correctness. Most static type systems completely rule out the possibility of huge classes of errors, and explicit types often make code more self-documenting. Even dynamically typed languages like Javascript are trying to retrofit some form of static typing (Typescript, Flow, etc).