All topics

Rust interview questions

24 questions with answers. 197 open jobs in India ask for Rust.

  1. What are the differences between Rust's `String` and `str`?

    String is the dynamic heap string type, like Vec: use it when you need to own or modify your string data.

    str is an immutable1 sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer. This means that str most commonly2 appears as &str: a reference to some UTF-8 data, normally called a "string slice" or just a "slice". A slice is just a view onto some data, and that data can be anywhere, e.g.

    • In static storage: a string literal "foo" is a &'static str. The data is hardcoded into the executable and loaded into memory when the program runs.

    • Inside a heap allocated String: String dereferences to a &str view of the String's data.

    • On the stack: e.g. the following creates a stack-allocated byte array, and then gets a view of that data as a &str:

      use std::str;
      let x: [u8; 3] = [b'a', b'b', b'c'];
      let stack_str: &str = str::from_utf8(&x).unwrap();
      

    In summary, use String if you need owned string data (like passing strings to other threads, or building them at runtime), and use &str if you only need a view of a string.

    This is identical to the relationship between a vector Vec<T> and a slice &[T], and is similar to the relationship between by-value T and by-reference &T for general types.

    1 A str is fixed-length; you cannot write bytes beyond the end, or leave trailing invalid bytes. Since UTF-8 is a variable-width encoding, this effectively forces all strs to be immutable in many cases. In general, mutation requires writing more or fewer bytes than there were before (e.g. replacing an a (1 byte) with an ä (2+ bytes) would require making more room in the str). There are specific methods that can modify a &mut str in place, mostly those that handle only ASCII characters, like make_ascii_uppercase.

    2 Dynamically sized types allow things like Rc<str> for a sequence of reference counted UTF-8 bytes since Rust 1.2. Rust 1.21 allows easily creating these types.

    From Stack Overflow: asked by Daniel Fath, answered by huon (CC BY-SA 4.0)

  2. Why doesn't println! work in Rust unit tests?

    This happens because Rust test programs hide the stdout of successful tests in order for the test output to be tidy. You can disable this behavior by passing the --nocapture option to the test binary or to cargo test (but, in this case after -- – see below):

    #[test]
    fn test() {
        println!("Hidden output")
    }
    

    Invoking tests:

    % rustc --test main.rs; ./main
    running 1 test
    test test ... ok
    test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
    % ./main --nocapture
    running 1 test
    Hidden output
    test test ... ok
    test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
    % cargo test -- --nocapture
    running 1 test
    Hidden output
    test test ... ok
    test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
    

    If tests fail, however, their stdout will be printed regardless if this option is present or not.

    From Stack Overflow: asked by ruipacheco, answered by Vladimir Matveev (CC BY-SA 4.0)

  3. What is the difference between iter and into_iter?

    TL;DR:

    • The iterator returned by into_iter may yield any of T, &T or &mut T, depending on the context.
    • The iterator returned by iter will yield &T, by convention.
    • The iterator returned by iter_mut will yield &mut T, by convention.

    The first question is: "What is into_iter?"

    into_iter comes from the IntoIterator trait:

    pub trait IntoIterator 
    where
        <Self::IntoIter as Iterator>::Item == Self::Item, 
    {
        type Item;
        type IntoIter: Iterator;
        fn into_iter(self) -> Self::IntoIter;
    }
    

    You implement this trait when you want to specify how a particular type is to be converted into an iterator. Most notably, if a type implements IntoIterator it can be used in a for loop.

    For example, Vec implements IntoIterator... thrice!

    impl<T> IntoIterator for Vec<T>
    impl<'a, T> IntoIterator for &'a Vec<T>
    impl<'a, T> IntoIterator for &'a mut Vec<T>
    

    Each variant is slightly different.

    This one consumes the Vec and its iterator yields values (T directly):

    impl<T> IntoIterator for Vec<T> {
        type Item = T;
        type IntoIter = IntoIter<T>;
        fn into_iter(mut self) -> IntoIter<T> { /* ... */ }
    }
    

    The other two take the vector by reference (don't be fooled by the signature of into_iter(self) because self is a reference in both cases) and their iterators will produce references to the elements inside Vec.

    This one yields immutable references:

    impl<'a, T> IntoIterator for &'a Vec<T> {
        type Item = &'a T;
        type IntoIter = slice::Iter<'a, T>;
        fn into_iter(self) -> slice::Iter<'a, T> { /* ... */ }
    }
    

    While this one yields mutable references:

    impl<'a, T> IntoIterator for &'a mut Vec<T> {
        type Item = &'a mut T;
        type IntoIter = slice::IterMut<'a, T>;
        fn into_iter(self) -> slice::IterMut<'a, T> { /* ... */ }
    }
    

    So:

    What is the difference between iter and into_iter?

    into_iter is a generic method to obtain an iterator, whether this iterator yields values, immutable references or mutable references is context dependent and can sometimes be surprising.

    iter and iter_mut are inherent methods. Their return type is therefore independent of the context, and will conventionally be iterators yielding immutable references and mutable references, respectively.

    The author of the Rust by Example post used Rust pre-1.53.0 to illustrate the surprise coming from the dependence on the context (i.e., the type) on which into_iter is called, and is also compounding the problem by using the fact that:

    1. Back then, IntoIterator was not implemented for [T; N], only for &[T; N] and &mut [T; N].
    2. When a method is not implemented for a value, it is automatically searched for references to that value instead

    which is very surprising for into_iter since all types (except [T; N]) implement it for all 3 variations (value and references).

    Read the rest at the sourceFrom Stack Overflow: asked by vitiral, answered by Matthieu M. (CC BY-SA 4.0)

  4. What is the syntax for a multiline string literal?

    All string literals can be broken across several lines; for example:

    let string = "line one
    line two";
    

    is a two line string, the same as "line one\nline two" (of course one can use the \n newline escape directly too). If you wish to just break a string across multiple lines for formatting reasons you can escape the newline and leading whitespace with a \; for example:

    let string = "one line \
        written over \
        several";
    

    is the same as "one line written over several".

    If you want linebreaks in the string you can add them before the \:

    let string = "multiple\n\
                  lines\n\
                  with\n\
                  indentation";
    

    It's the same as "multiple\nlines\nwith\nindentation";

    From Stack Overflow: asked by Dumbapples, answered by huon (CC BY-SA 4.0)

  5. Why are Rust executables so huge?

    Rust uses static linking to compile its programs, meaning that all libraries required by even the simplest Hello world! program will be compiled into your executable. This also includes the Rust runtime.

    To force Rust to dynamically link programs, use the command-line arguments -C prefer-dynamic; this will result in a much smaller file size but will also require the Rust libraries (including its runtime) to be available to your program at runtime. This essentially means you will need to provide them if the computer does not have them, taking up more space than your original statically linked program takes up.

    For portability I'd recommend you statically link the Rust libraries and runtime in the way you have been doing if you were to ever distribute your programs to others.

    From Stack Overflow: asked by BitTickler, answered by AStopher (CC BY-SA 3.0)

  6. What are Rust's exact auto-dereferencing rules?

    Your pseudo-code is pretty much correct. For this example, suppose we had a method call foo.bar() where foo: T. I'm going to use the fully qualified syntax (FQS) to be unambiguous about what type the method is being called with, e.g. A::bar(foo) or A::bar(&***foo). I'm just going to write a pile of random capital letters, each one is just some arbitrary type/trait, except T is always the type of the original variable foo that the method is called on.

    The core of the algorithm is:

    • For each "dereference step" U (that is, set U = T and then U = *T, ...)
      1. if there's a method bar where the receiver type (the type of self in the method) matches U exactly , use it (a "by value method")
      2. otherwise, add one auto-ref (take & or &mut of the receiver), and, if some method's receiver matches &U, use it (an "autorefd method")

    Notably, everything considers the "receiver type" of the method, not the Self type of the trait, i.e. impl ... for Foo { fn method(&self) {} } thinks about &Foo when matching the method, and fn method2(&mut self) would think about &mut Foo when matching.

    It is an error if there's ever multiple trait methods valid in the inner steps (that is, there can be only be zero or one trait methods valid in each of 1. or 2., but there can be one valid for each: the one from 1 will be taken first), and inherent methods take precedence over trait ones. It's also an error if we get to the end of the loop without finding anything that matches. It is also an error to have recursive Deref implementations, which make the loop infinite (they'll hit the "recursion limit").

    These rules seem to do-what-I-mean in most circumstances, although having the ability to write the unambiguous FQS form is very useful in some edge cases, and for sensible error messages for macro-generated code.

    Only one auto-reference is added because

    • if there was no bound, things get bad/slow, since every type can have an arbitrary number of references taken
    • taking one reference &foo retains a strong connection to foo (it is the address of foo itself), but taking more starts to lose it: &&foo is the address of some temporary variable on the stack that stores &foo.

    Examples

    Suppose we have a call foo.refm(), if foo has type:

    Read the rest at the sourceFrom Stack Overflow: asked by kFYatek, answered by huon (CC BY-SA 4.0)

  7. What's the de-facto way of reading and writing files in Rust 1.x?

    None of the functions I show here panic on their own, but I am using expect because I don't know what kind of error handling will fit best into your application. Go read The Rust Programming Language's chapter on error handling to understand how to appropriately handle failure in your own program.

    Rust 1.26 and onwards

    If you don't want to care about the underlying details, there are one-line functions for reading and writing.

    Read a file to a String

    use std::fs;
    fn main() {
        let data = fs::read_to_string("/etc/hosts").expect("Should be able to read hosts file");
        println!("{}", data);
    }
    

    Read a file as a Vec<u8>

    use std::fs;
    fn main() {
        let data = fs::read("/etc/hosts").expect("Should be able to read hosts file");
        println!("{}", data.len());
    }
    

    Write a file

    use std::fs;
    fn main() {
        let data = "Some data!";
        fs::write("/tmp/foo", data).expect("Should be able to write to `/foo/tmp`");
    }
    

    Rust 1.0 and onwards

    These forms are slightly more verbose than the one-line functions that allocate a String or Vec for you, but are more powerful in that you can reuse allocated data or append to an existing object.

    Reading data

    Reading a file requires two core pieces: File and Read.

    Read a file to a String

    use std::fs::File;
    use std::io::Read;
    fn main() {
        let mut data = String::new();
        let mut f = File::open("/etc/hosts").expect("Should be able to open `/etc/hosts`");
        f.read_to_string(&mut data).expect("Should be able to read to string");
        println!("{}", data);
    }
    

    Read a file as a Vec<u8>

    use std::fs::File;
    use std::io::Read;
    fn main() {
        let mut data = Vec::new();
        let mut f = File::open("/etc/hosts").expect("Should be able to open `/etc/hosts`");
        f.read_to_end(&mut data).expect("Should be able to read data");
        println!("{}", data.len());
    }
    

    Write a file

    Writing a file is similar, except we use the Write trait and we always write out bytes. You can convert a String / &str to bytes with as_bytes:

    use std::fs::File;
    use std::io::Write;
    fn main() {
        let data = "Some data!";
        let mut f = File::create("/tmp/foo").expect("Should be able to create file");
        f.write_all(data.as_bytes()).expect("Should be able to write data");
    }
    

    Buffered I/O

    I felt a bit of a push from the community to use BufReader and BufWriter instead of reading straight from a file

    A buffered reader (or writer) uses a buffer to reduce the number of I/O requests. For example, it's much more efficient to access the disk once to read 256 bytes instead of accessing the disk 256 times.

    That being said, I don't believe a buffered reader/writer will be useful when reading the entire file. read_to_end seems to copy data in somewhat large chunks, so the transfer may already be naturally coalesced into fewer I/O requests.

    Here's an example of using it for reading:

    use std::fs::File;
    use std::io::{BufReader, Read};
    fn main() {
        let mut data = String::new();
        let f = File::open("/etc/hosts").expect("Should be able to open `/etc/hosts`");
        let mut br = BufReader::new(f);
        br.read_to_string(&mut data).expect("Should be able to read to string");
        println!("{}", data);
    }
    

    Read the rest at the sourceFrom Stack Overflow: asked by Jared, answered by Shepmaster (CC BY-SA 4.0)

  8. Is there a command to update Cargo to the latest official release?

    You should update rustc and cargo based on how you installed it. If you used rustup, a rustup update should suffice. If you used a package manager or a binary installer, check those sources for an update.

    rustc and cargo are shipped together, but that doesn't mean that their versions need to match. In fact, they do not match until Rust 1.26.0, when the Cargo binary was changed to print the Rust version.

    I have the same versions of rustc and cargo that you do; those are the ones that correspond to the Rust 1.9 release. There's nothing to worry about.

    If you really want to, you can download a nightly version of Cargo or compile your own. As long as your version exists in your PATH before the older one, it will be used.

    I used to do this with my local Rust builds in order to have a version of Cargo at all, although rustup now automatically uses the cargo from the most recent stable version when there isn't one available in the current toolchain, which is nice.

    From Stack Overflow: asked by Filip Allberg, answered by Shepmaster (CC BY-SA 4.0)

  9. What is this question mark operator about?

    As you may have noticed, Rust does not have exceptions. It has panics, but their use for error-handling is discouraged (they are meant for unrecoverable errors).

    In Rust, error handling uses Result. A typical example would be:

    fn halves_if_even(i: i32) -> Result<i32, Error> {
        if i % 2 == 0 {
            Ok(i / 2)
        } else {
            Err(/* something */)
        }
    }
    fn do_the_thing(i: i32) -> Result<i32, Error> {
        let i = match halves_if_even(i) {
            Ok(i) => i,
            Err(e) => return Err(e),
        };
        // use `i`
    }
    

    This is great because:

    • when writing the code you cannot accidentally forget to deal with the error,
    • when reading the code you can immediately see that there is a potential for error right here.

    It's less than ideal, however, in that it is very verbose. This is where the question mark operator ? comes in.

    The above can be rewritten as:

    fn do_the_thing(i: i32) -> Result<i32, Error> {
        let i = halves_if_even(i)?;
        // use `i`
    }
    

    which is much more concise.

    What ? does here is equivalent to the match statement above with an addition. In short:

    1. It unpacks the Result if OK
    2. It returns the error if not, calling From::from on the error value to potentially convert it to another type.

    It's a bit magic, but error handling needs some magic to cut down the boilerplate, and unlike exceptions it is immediately visible which function calls may or may not error out: those that are adorned with ?.

    One example of the magic is that this also works for Option:

    // Assume
    // fn halves_if_even(i: i32) -> Option<i32>
    fn do_the_thing(i: i32) -> Option<i32> {
        let i = halves_if_even(i)?;
        // use `i`
    }
    

    The ? operator, stabilized in Rust version 1.13.0 is powered by the (unstable) Try trait.

    See also:

    From Stack Overflow: asked by Angel Angel, answered by Matthieu M. (CC BY-SA 4.0)

  10. What is the equivalent of the join operator over a vector of Strings?

    In Rust 1.3.0 and later, join is available:

    fn main() {
        let string_list = vec!["Foo".to_string(),"Bar".to_string()];
        let joined = string_list.join("-");
        assert_eq!("Foo-Bar", joined);
    }
    

    Before 1.3.0 this method was called connect:

    let joined = string_list.connect("-");
    

    Note that you do not need to import anything since the methods are automatically imported by the standard library prelude.

    join copies elements of the vector, it does not move them, thus it preserves the contents of the vector, rather than destroying it.

    From Stack Overflow: asked by Davide Aversa, answered by MatthewG (CC BY-SA 4.0)

  11. What is the difference between Copy and Clone?

    Clone is designed for arbitrary duplications: a Clone implementation for a type T can do arbitrarily complicated operations required to create a new T. It is a normal trait (other than being in the prelude), and so requires being used like a normal trait, with method calls, etc.

    The Copy trait represents values that can be safely duplicated via memcpy: things like reassignments and passing an argument by-value to a function are always memcpys, and so for Copy types, the compiler understands that it doesn't need to consider those a move.

    From Stack Overflow: asked by user12341234, answered by huon (CC BY-SA 3.0)

  12. Why are explicit lifetimes needed in Rust?

    The other answers all have salient points (fjh's concrete example where an explicit lifetime is needed), but are missing one key thing: why are explicit lifetimes needed when the compiler will tell you you've got them wrong?

    This is actually the same question as "why are explicit types needed when the compiler can infer them". A hypothetical example:

    fn foo() -> _ {  
        ""
    }
    

    Of course, the compiler can see that I'm returning a &'static str, so why does the programmer have to type it?

    The main reason is that while the compiler can see what your code does, it doesn't know what your intent was.

    Functions are a natural boundary to firewall the effects of changing code. If we were to allow lifetimes to be completely inspected from the code, then an innocent-looking change might affect the lifetimes, which could then cause errors in a function far away. This isn't a hypothetical example. As I understand it, Haskell has this problem when you rely on type inference for top-level functions. Rust nipped that particular problem in the bud.

    There is also an efficiency benefit to the compiler — only function signatures need to be parsed in order to verify types and lifetimes. More importantly, it has an efficiency benefit for the programmer. If we didn't have explicit lifetimes, what does this function do:

    fn foo(a: &u8, b: &u8) -> &u8
    

    It's impossible to tell without inspecting the source, which would go against a huge number of coding best practices.

    by inferring an illegal assignment of a reference to a wider scope

    Scopes are lifetimes, essentially. A bit more clearly, a lifetime 'a is a generic lifetime parameter that can be specialized with a specific scope at compile time, based on the call site.

    are explicit lifetimes actually needed to prevent [...] errors?

    Not at all. Lifetimes are needed to prevent errors, but explicit lifetimes are needed to protect what little sanity programmers have.

    From Stack Overflow: asked by corazza, answered by Shepmaster (CC BY-SA 3.0)

  13. Why is it discouraged to accept a reference &String, &Vec, or &Box as a function argument?

    TL;DR: One can instead use &str, &[T] or &T to allow for more generic code.

    1. One of the main reasons to use a String or a Vec is because they allow increasing or decreasing the capacity. However, when you accept an immutable reference, you cannot use any of those interesting methods on the Vec or String.

    2. Accepting a &String, &Vec or &Box also requires the argument to be allocated on the heap before you can call the function. Accepting a &str allows a string literal (saved in the program data) and accepting a &[T] or &T allows a stack-allocated array or variable. Unnecessary allocation is a performance loss. This is usually exposed right away when you try to call these methods in a test or a main method:

      awesome_greeting(&String::from("Anna"));
      
      total_price(&vec![42, 13, 1337])
      
      is_even(&Box::new(42))
      
    3. Another performance consideration is that &String, &Vec and &Box introduce an unnecessary layer of indirection as you have to dereference the &String to get a String and then perform a second dereference to end up at &str.

    Instead, you should accept a string slice (&str), a slice (&[T]), or just a reference (&T). A &String, &Vec<T> or &Box<T> will be automatically coerced (via deref coercion) to a &str, &[T] or &T, respectively.

    fn awesome_greeting(name: &str) {
        println!("Wow, you are awesome, {}!", name);
    }
    
    fn total_price(prices: &[i32]) -> i32 {
        prices.iter().sum()
    }
    
    fn is_even(value: &i32) -> bool {
        *value % 2 == 0
    }
    

    Now you can call these methods with a broader set of types. For example, awesome_greeting can be called with a string literal ("Anna") or an allocated String. total_price can be called with a reference to an array (&[1, 2, 3]) or an allocated Vec.

    If you'd like to add or remove items from the String or Vec<T>, you can take a mutable reference (&mut String or &mut Vec<T>):

    fn add_greeting_target(greeting: &mut String) {
        greeting.push_str("world!");
    }
    
    fn add_candy_prices(prices: &mut Vec<i32>) {
        prices.push(5);
        prices.push(25);
    }
    

    Specifically for slices, you can also accept a &mut [T] or &mut str. This allows you to mutate a specific value inside the slice, but you cannot change the number of items inside the slice (which means it's very restricted for strings):

    fn reset_first_price(prices: &mut [i32]) {
        prices[0] = 0;
    }
    
    fn lowercase_first_ascii_character(s: &mut str) {
        if let Some(f) = s.get_mut(0..1) {
            f.make_ascii_lowercase();
        }
    }
    

    From Stack Overflow: asked by Shepmaster, answered by Shepmaster (CC BY-SA 4.0)

  14. What is the best way to concatenate vectors in Rust?

    The structure std::vec::Vec has method append():

    fn append(&mut self, other: &mut Vec<T>)
    

    Moves all the elements of other into Self, leaving other empty.

    From your example, the following code will concatenate two vectors by mutating a and b:

    fn main() {
        let mut a = vec![1, 2, 3];
        let mut b = vec![4, 5, 6];
        a.append(&mut b);
        assert_eq!(a, [1, 2, 3, 4, 5, 6]);
        assert_eq!(b, []);
    }
    

    Alternatively, you can use Extend::extend() to append all elements of something that can be turned into an iterator (like Vec) to a given vector:

    let mut a = vec![1, 2, 3];
    let b = vec![4, 5, 6];
    a.extend(b);
    assert_eq!(a, [1, 2, 3, 4, 5, 6]);
    // b is moved and can't be used anymore
    

    Note that the vector b is moved instead of emptied. If your vectors contain elements that implement Copy, you can pass an immutable reference to one vector to extend() instead in order to avoid the move. In that case the vector b is not changed:

    let mut a = vec![1, 2, 3];
    let b = vec![4, 5, 6];
    a.extend(&b);
    assert_eq!(a, [1, 2, 3, 4, 5, 6]);
    assert_eq!(b, [4, 5, 6]);
    

    From Stack Overflow: asked by Joe Thomas, answered by user4268862 (CC BY-SA 3.0)

  15. Why is there a large performance impact when looping over an array with 240 or more elements?

    Summary: below 240, LLVM fully unrolls the inner loop and that lets it notice it can optimize away the repeat loop, breaking your benchmark.


    You found a magic threshold above which LLVM stops performing certain optimizations. The threshold is 8 bytes * 240 = 1920 bytes (your array is an array of usizes, therefore the length is multiplied with 8 bytes, assuming x86-64 CPU). In this benchmark, one specific optimization – only performed for length 239 – is responsible for the huge speed difference. But let's start slowly:

    (All code in this answer is compiled with -C opt-level=3)

    pub fn foo() -> usize {
        let arr = [0; 240];
        let mut s = 0;
        for i in 0..arr.len() {
            s += arr[i];
        }
        s
    }
    

    This simple code will produce roughly the assembly one would expect: a loop adding up elements. However, if you change 240 to 239, the emitted assembly differs quite a lot. See it on Godbolt Compiler Explorer. Here is a small part of the assembly:

    movdqa  xmm1, xmmword ptr [rsp + 32]
    movdqa  xmm0, xmmword ptr [rsp + 48]
    paddq   xmm1, xmmword ptr [rsp]
    paddq   xmm0, xmmword ptr [rsp + 16]
    paddq   xmm1, xmmword ptr [rsp + 64]
    ; more stuff omitted here ...
    paddq   xmm0, xmmword ptr [rsp + 1840]
    paddq   xmm1, xmmword ptr [rsp + 1856]
    paddq   xmm0, xmmword ptr [rsp + 1872]
    paddq   xmm0, xmm1
    pshufd  xmm1, xmm0, 78
    paddq   xmm1, xmm0
    

    This is what's called loop unrolling: LLVM pastes the loop body a bunch of time to avoid having to execute all those "loop management instructions", i.e. incrementing the loop variable, check if the loop has ended and the jump to the start of the loop.

    In case you're wondering: the paddq and similar instructions are SIMD instructions which allow summing up multiple values in parallel. Moreover, two 16-byte SIMD registers (xmm0 and xmm1) are used in parallel so that instruction-level parallelism of the CPU can basically execute two of these instructions at the same time. After all, they are independent of one another. In the end, both registers are added together and then horizontally summed down to the scalar result.

    Modern mainstream x86 CPUs (not low-power Atom) really can do 2 vector loads per clock when they hit in L1d cache, and paddq throughput is also at least 2 per clock, with 1 cycle latency on most CPUs. See https://agner.org/optimize/ and also this Q&A about multiple accumulators to hide latency (of FP FMA for a dot product) and bottleneck on throughput instead.

    LLVM does unroll small loops some when it's not fully unrolling, and still uses multiple accumulators. So usually, front-end bandwidth and back-end latency bottlenecks aren't a huge problem for LLVM-generated loops even without full unrolling.

    But loop unrolling is not responsible for a performance difference of factor 80! At least not loop unrolling alone. Let's take a look at the actual benchmarking code, which puts the one loop inside another one:

    const CAPACITY: usize = 239;
    const IN_LOOPS: usize = 500000;
    pub fn foo() -> usize {
        let mut arr = [0; CAPACITY];
        for i in 0..CAPACITY {
            arr[i] = i;
        }
        let mut sum = 0;
        for _ in 0..IN_LOOPS {
            let mut s = 0;
            for i in 0..arr.len() {
                s += arr[i];
            }
            sum += s;
        }
        sum
    }
    

    (On Godbolt Compiler Explorer)

    The assembly for CAPACITY = 240 looks normal: two nested loops. (At the start of the function there is quite some code just for initializing, which we will ignore.) For 239, however, it looks very different! We see that the initializing loop and the inner loop got unrolled: so far so expected.

    Read the rest at the sourceFrom Stack Overflow: asked by Guy Korland, answered by Lukas Kalbertodt (CC BY-SA 4.0)

  16. When does a closure implement Fn, FnMut and FnOnce?

    The traits each represent more and more restrictive properties about closures/functions, indicated by the signatures of their call_... method, and particularly the type of self:

    • FnOnce (self) are functions that can be called once
    • FnMut (&mut self) are functions that can be called if they have &mut access to their environment
    • Fn (&self) are functions that can be called if they only have & access to their environment

    A closure |...| ... will automatically implement as many of those as it can.

    • All closures implement FnOnce: a closure that can't be called once doesn't deserve the name. Note that if a closure only implements FnOnce, it can be called only once.
    • Closures that don't move out of their captures implement FnMut, allowing them to be called more than once (if there is unaliased access to the function object).
    • Closures that don't need unique/mutable access to their captures implement Fn, allowing them to be called essentially everywhere.

    These restrictions follow directly from the type of self and the "desugaring" of closures into structs; described in my blog post Finding Closure in Rust.

    For information on closures, see Closures: Anonymous Functions that Can Capture Their Environment in The Rust Programming Language.

    From Stack Overflow: asked by Denilson Amorim, answered by huon (CC BY-SA 4.0)

  17. Is it possible to use global variables in Rust?

    It's possible, but heap allocation is not allowed directly. Heap allocation is performed at runtime. Here are a few examples:

    static SOME_INT: i32 = 5;
    static SOME_STR: &'static str = "A static string";
    static SOME_STRUCT: MyStruct = MyStruct {
        number: 10,
        string: "Some string",
    };
    static mut db: Option<sqlite::Connection> = None;
    fn main() {
        println!("{}", SOME_INT);
        println!("{}", SOME_STR);
        println!("{}", SOME_STRUCT.number);
        println!("{}", SOME_STRUCT.string);
        unsafe {
            db = Some(open_database());
        }
    }
    struct MyStruct {
        number: i32,
        string: &'static str,
    }
    

    From Stack Overflow: asked by Brian Oh, answered by Ercan Erden (CC BY-SA 4.0)

  18. Is there a faster/shorter way to initialize variables in a Rust struct?

    You can provide default values for your struct by implementing the Default trait. The default function would look like your current new function:

    impl Default for cParams {
        fn default() -> cParams {
            cParams {
                iInsertMax: -1,
                iUpdateMax: -1,
                iDeleteMax: -1,
                iInstanceMax: -1,
                tFirstInstance: false,
                tCreateTables: false,
                tContinue: false,
            }
        }
    }
    

    You can then instantiate the struct by giving only the non-default values:

    let p = cParams { iInsertMax: 10, ..Default::default() };
    

    With some minor changes to your data structure, you can take advantage of an automatically derived default implementation. If you use #[derive(Default)] on a data structure, the compiler will automatically create a default function for you that fills each field with its default value. The default boolean value is false, the default integral value is 0.

    An integer's default value being 0 is a problem here since you want the integer fields to be -1 by default. You could define a new type that implements a default value of -1 and use that instead of i64 in your struct. (I haven't tested that, but it should work).

    However, I'd suggest to slightly change your data structure and use Option<i64> instead of i64. I don't know the context of your code, but it looks like you're using the special value of -1 to represent the special meaning "infinite", or "there's no max". In Rust, we use an Option to represent an optionally present value. There's no need for a -1 hack. An option can be either None or Some(x) where x would be your i64 here. It might even be an unsigned integer if -1 was the only negative value. The default Option value is None, so with the proposed changes, your code could look like this:

    #[derive(Default)]
    struct cParams {
        iInsertMax: Option<u64>,
        iUpdateMax: Option<u64>,
        iDeleteMax: Option<u64>,
        iInstanceMax: Option<u64>,
        tFirstInstance: bool,
        tCreateTables: bool,
        tContinue: bool,
    }
    let p = cParams { iInsertMax: Some(10), ..Default::default() };
    

    From Stack Overflow: asked by Brian Oh, answered by Zargony (CC BY-SA 3.0)

  19. What is the correct way to return an Iterator (or any other trait)?

    I've found it useful to let the compiler guide me:

    fn to_words(text: &str) { // Note no return type
        text.split(' ')
    }
    

    Compiling gives:

    error[E0308]: mismatched types
     --> src/lib.rs:5:5
      |
    5 |     text.split(' ')
      |     ^^^^^^^^^^^^^^^ expected (), found struct `std::str::Split`
      |
      = note: expected type `()`
                 found type `std::str::Split<'_, char>`
    help: try adding a semicolon
      |
    5 |     text.split(' ');
      |                    ^
    help: try adding a return type
      |
    3 | fn to_words(text: &str) -> std::str::Split<'_, char> {
      |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    Following the compiler's suggestion and copy-pasting that as my return type (with a little cleanup):

    use std::str;
    fn to_words(text: &str) -> str::Split<'_, char> {
        text.split(' ')
    }
    

    The problem is that you cannot return a trait like Iterator because a trait doesn't have a size. That means that Rust doesn't know how much space to allocate for the type. You cannot return a reference to a local variable, either, so returning &dyn Iterator is a non-starter.

    Impl trait

    As of Rust 1.26, you can use impl trait:

    fn to_words<'a>(text: &'a str) -> impl Iterator<Item = &'a str> {
        text.split(' ')
    }
    fn main() {
        let text = "word1 word2 word3";
        println!("{}", to_words(text).take(2).count());
    }
    

    There are restrictions on how this can be used. You can only return a single type (no conditionals!) and it must be used on a free function or an inherent implementation.

    Boxed

    If you don't mind losing a little bit of efficiency, you can return a Box<dyn Iterator>:

    fn to_words<'a>(text: &'a str) -> Box<dyn Iterator<Item = &'a str> + 'a> {
        Box::new(text.split(' '))
    }
    fn main() {
        let text = "word1 word2 word3";
        println!("{}", to_words(text).take(2).count());
    }
    

    This is the primary option that allows for dynamic dispatch. That is, the exact implementation of the code is decided at run-time, rather than compile-time. That means this is suitable for cases where you need to return more than one concrete type of iterator based on a condition.

    Newtype

    use std::str;
    struct Wrapper<'a>(str::Split<'a, char>);
    impl<'a> Iterator for Wrapper<'a> {
        type Item = &'a str;
        fn next(&mut self) -> Option<&'a str> {
            self.0.next()
        }
        fn size_hint(&self) -> (usize, Option<usize>) {
            self.0.size_hint()
        }
    }
    fn to_words(text: &str) -> Wrapper<'_> {
        Wrapper(text.split(' '))
    }
    fn main() {
        let text = "word1 word2 word3";
        println!("{}", to_words(text).take(2).count());
    }
    

    Type alias

    As pointed out by reem

    use std::str;
    type MyIter<'a> = str::Split<'a, char>;
    fn to_words(text: &str) -> MyIter<'_> {
        text.split(' ')
    }
    fn main() {
        let text = "word1 word2 word3";
        println!("{}", to_words(text).take(2).count());
    }
    

    Dealing with closures

    When impl Trait isn't available for use, closures make things more complicated. Closures create anonymous types and these cannot be named in the return type:

    fn odd_numbers() -> () {
        (0..100).filter(|&v| v % 2 != 0)
    }
    
    found type `std::iter::Filter<std::ops::Range<{integer}>, [closure@src/lib.rs:4:21: 4:36]>`
    

    In certain cases, these closures can be replaced with functions, which can be named:

    Read the rest at the sourceFrom Stack Overflow: asked by forgemo, answered by Shepmaster (CC BY-SA 4.0)

  20. What's the difference between use and extern crate?

    extern crate foo indicates that you want to link against an external library and brings the top-level crate name into scope (equivalent to use foo). As of Rust 2018, in most cases you won't need to use extern crate anymore because Cargo informs the compiler about what crates are present. (There are one or two exceptions)

    use bar is a shorthand for referencing fully-qualified symbols.

    Theoretically, the language doesn't need use — you could always just fully-qualify the names, but typing std::collections::HashMap.new(...) would get very tedious! Instead, you can just type use std::collections::HashMap once and then HashMap will refer to that.

    From Stack Overflow: asked by maralla, answered by Shepmaster (CC BY-SA 4.0)

  21. How do I concatenate strings?

    When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str:

    fn main() {
        let mut owned_string: String = "hello ".to_owned();
        let borrowed_string: &str = "world";
        
        owned_string.push_str(borrowed_string);
        println!("{owned_string}");
    }
    

    Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String, as &String can be dereferenced as &str.

    fn main() {
        let mut owned_string: String = "hello ".to_owned();
        let another_owned_string: String = "world".to_owned();
        
        owned_string.push_str(&another_owned_string);
        println!("{owned_string}");
    }
    

    After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

    fn main() {
        let owned_string: String = "hello ".to_owned();
        let borrowed_string: &str = "world";
        
        let new_owned_string = owned_string + borrowed_string;
        println!("{new_owned_string}");
    }
    

    Note that owned_string is no longer accessible after the call to +.

    What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!:

    fn main() {
        let borrowed_string: &str = "hello ";
        let another_borrowed_string: &str = "world";
        
        let together = format!("{borrowed_string}{another_borrowed_string}");
        println!("{}", together);
    }
    

    Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String, we can use the fact that String also can be formatted:

    fn main() {
        let owned_string: String = "hello ".to_owned();
        let another_owned_string: String = "world".to_owned();
        
        let together = format!("{owned_string}{another_owned_string}");
        println!("{}", together);
    }
    

    You don't have to use format! though. You can clone one string and append the other string to the new string:

    fn main() {
        let owned_string: String = "hello ".to_owned();
        let borrowed_string: &str = "world";
        
        let together = owned_string.clone() + borrowed_string;
        println!("{together}");
    }
    

    Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!

    From Stack Overflow: asked by jsalter, answered by Shepmaster (CC BY-SA 4.0)

  22. How do you disable dead code warnings at the crate level in Rust?

    You can either:

    • Add an allow attribute on a struct, module, function, etc.:

      #[allow(dead_code)]
      struct SemanticDirection;
      
    • Add an allow as a crate-level attribute; notice the !:

      #![allow(dead_code)]
      
    • Pass it to rustc:

      rustc -A dead_code main.rs
      
    • Pass it using cargo via the RUSTFLAGS environment variable:

      RUSTFLAGS="$RUSTFLAGS -A dead_code" cargo build
      

    From Stack Overflow: asked by Andrew Wagner, answered by Arjan (CC BY-SA 4.0)

  23. Convert a String to int?

    You can directly convert to an int using the str::parse::<T>() method, which returns a Result containing the int.

    let my_string = "27".to_string();  // `parse()` works with `&str` and `String`!
    let my_int = my_string.parse::<i32>().unwrap();
    

    You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:

    let my_int: i32 = my_string.parse().unwrap();
    

    Since parse() returns a Result, it will either be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32), or an Ok with the value in it.

    From Stack Overflow: asked by mmtauqir, answered by John Vrbanac (CC BY-SA 4.0)

  24. How do I print the type of a variable in Rust?

    You can use the std::any::type_name function. This doesn't need a nightly compiler or an external crate, and the results are quite correct:

    fn print_type_of<T>(_: &T) {
        println!("{}", std::any::type_name::<T>());
    }
    fn main() {
        let s = "Hello";
        let i = 42;
        print_type_of(&s); // &str
        print_type_of(&i); // i32
        print_type_of(&main); // playground::main
        print_type_of(&print_type_of::<i32>); // playground::print_type_of<i32>
        print_type_of(&{ || "Hi!" }); // playground::main::{{closure}}
    }
    

    Be warned: as said in the documentation, this information must be used for a debug purpose only:

    This is intended for diagnostic use. The exact contents and format of the string are not specified, other than being a best-effort description of the type.

    If you want your type representation to stay the same between compiler versions, you should use a trait, like in the phicr's answer.

    From Stack Overflow: asked by user2431012, answered by Boiethios (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.