PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label rust. Show all posts
Showing posts with label rust. Show all posts

Thursday, December 22, 2022

[FIXED] What is "0is" notation in Rust?

 December 22, 2022     rust, rust-obsolete, syntax     No comments   

Issue

As seen in this repository:

https://github.com/ReactiveX/RxRust/blob/master/src/lib.rs#L110

let gen = move |:| {
    let it = range(0is, 20is);
    //             ~~~  ~~~~
    let q   = Box::new(Decoupler::new(dtx.clone()));
    let mut map1 = Box::new(Map::new(|i : isize| {i * 10}));
    let mut map2 = Box::new(Map::new(|i : isize| {i + 2}));
    let mut iter = Box::new(IterPublisher::new(it));


    map2.subscribe(q);
    map1.subscribe(map2);
    iter.subscribe(map1);
};

(squiggly emphasis mine)

I'm trying to figure out what is after a numeral is. The Book says about literal suffixes only briefly:

Note that all number literals except the byte literal allow a type suffix, such as 57u8, and _ as a visual separator, such as 1_000.

— https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types

And the compiler (1.53) only understands a set of specific suffixes, so I could not even get the original crate built on my machine:

invalid suffix `is`
help: the suffix must be one of the numeric types (`u32`, `isize`, `f32`, etc.)

Is it some sort of archaic syntax, or is it me missing something?


Solution

In the old, pre 1.0, times, integer suffixes were a little different.

Thanks to the Wayback Machine, we can take a peek to the past:

There are 10 valid values for an integer suffix: \

  • The is and us suffixes give the literal type isize or usize, respectively.
  • Each of the signed and unsigned machine types u8, i8, u16, i16, u32, i32, u64 and i64 give the literal the corresponding machine type.

But in Rust 1.0 the first bullet went away and now you write 20isize instead of 20is.



Answered By - rodrigo
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, December 20, 2022

[FIXED] What does the ampersand (&) before `self` mean in Rust?

 December 20, 2022     rust, syntax, variables     No comments   

Issue

I've seen this code in the Rust documentation:

fn eat(&self) {
    println!("{} is done eating.", self.name);
}

what does the & in &self mean?


Solution

This means you'll be passing in a reference to the object, as opposed to moving the object itself. It's important to distinguish this because if your function looked like:

fn eat(self) {
    println!("{} is done eating.", self.name);
}

and you tried calling it then using the variable after, you'd get an error

object = Foo::new();
object.eat();
object.something(); // error, because you moved object in eat

because when you don't specify &, rust moves the value into the function and your original binding no longer has ownership. check out this minimal example I created (playground version):

struct Foo {
    x : u32
}

impl Foo {

    fn eat(self) {
        println!("eating");
    }

    fn something(&self) {
        println!("else");
    }

}

fn main() {
    println!("Hello, world!");

    let g = Foo { x: 5 };
    g.eat();
    g.something();  // if this comes before eat, no errors because we arent moving
}

Now switch something to be called before eat. Because something only takes a reference, g still has ownership and you can continue on. eat on the other hand moves g and you no longer can use g.



Answered By - Syntactic Fructose
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, December 14, 2022

[FIXED] How to partially initialize an ArrayVec?

 December 14, 2022     initialization, rust, syntax     No comments   

Issue

I need structures with fixed maximum size, so the obvious choice seem to be arrayvec crate. However, I'm stuck when ArrayVec is a member of a structure that later needs to be partially initialised:

use arrayvec::ArrayVec; // 0.4.7

#[derive(Debug)]
struct Test {
    member_one: Option<u32>,
    member_two: ArrayVec<[u16; 5]>,
}

pub fn main() {
    let mut test = Test {
        member_one: Some(45678),
        member_two: [1, 2, 3], // <- What to do here to initialise only 3 elements?
    };

    print!("{:?}", test);
}

I'd like to initialise the first three elements of the ArrayVec as it's perfectly capable of holding any number of elements from zero to 5 (in my example), but I can't figure out how to do it.


Solution

You can collect into an ArrayVec from an iterator:

let mut test = Test {
    member_one: Some(45678),
    member_two: [1, 2, 3].into_iter().collect(),
};


Answered By - Peter Hall
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, December 13, 2022

[FIXED] What is the r#""# operator in Rust?

 December 13, 2022     rust, string, string-literals, syntax     No comments   

Issue

I saw the operator r#"" in Rust but I can't find what it does. It came in handy for creating JSON:

let var1 = "test1";
let json = r#"{"type": "type1", "type2": var1}"#;
println!("{}", json) // => {"type2": "type1", "type2": var1}

What's the name of the operator r#""? How do I make var1 evaluate?


Solution

I can't find what it does

It has to do with string literals and raw strings. I think it is explained pretty well in this part of the documentation, in the code block that is posted there you can see what it does:

"foo"; r"foo";                     // foo
"\"foo\""; r#""foo""#;             // "foo"

"foo #\"# bar";
r##"foo #"# bar"##;                // foo #"# bar

"\x52"; "R"; r"R";                 // R
"\\x52"; r"\x52";                  // \x52

It negates the need to escape special characters inside the string.



Answered By - Tim
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the r#""# operator in Rust?

 December 13, 2022     rust, string, string-literals, syntax     No comments   

Issue

I saw the operator r#"" in Rust but I can't find what it does. It came in handy for creating JSON:

let var1 = "test1";
let json = r#"{"type": "type1", "type2": var1}"#;
println!("{}", json) // => {"type2": "type1", "type2": var1}

What's the name of the operator r#""? How do I make var1 evaluate?


Solution

I can't find what it does

It has to do with string literals and raw strings. I think it is explained pretty well in this part of the documentation, in the code block that is posted there you can see what it does:

"foo"; r"foo";                     // foo
"\"foo\""; r#""foo""#;             // "foo"

"foo #\"# bar";
r##"foo #"# bar"##;                // foo #"# bar

"\x52"; "R"; r"R";                 // R
"\\x52"; r"\x52";                  // \x52

It negates the need to escape special characters inside the string.



Answered By - Tim
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, December 12, 2022

[FIXED] What does "|_|" mean in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

I am learning how to connect database to Rust program. There something I don't quite understand:

PgConnection::establish(&database_url).unwrap_or_else(|_| panic!("Error connecting to {}", database_url))

What does this expression mean? What does |_| mean?


Solution

Ignoring the underscore _ for now, Rust uses pipes | to delimit the parameter-list of a closure (aka lambda-function, anonymous function, etc). For comparison, JavaScript and C# use normal parentheses and a fat arrow ( ) => to denote their closures (a closure is just an anonymous function with environment capture semantics), like so:

// JavaScript:
const smallerArray = bigArray.filter( ( x, idx ) => idx < 5 );

// C#:
T[] smallerArray = bigArray.Where( ( T item, Int32 idx ) => idx < 5 ).ToArray();

Instead of being a conformist and using ( ) => like everyone else, Rust opts for a different syntax for the parameter-list: it uses |a, b, c| for single-line functions and |a, b, c| { stuff } for multi-line functions, and without any arrow symbology.

...so the above JavaScript and C# would be translated into Rust like so:

let smaller_array = big_array.into_iter().filter( |item| item < 5 )

As for the underscore: Rust shares C#'s convention for using an underscore to denote a discarded or otherwise ignored parameter or local. Now you might wonder what the point of a discarded parameter is: why not just omit it entirely like in JavaScript? (e.g. bigArray.filter( x => x < 5 ) and bigArray.filter( ( x, idx ) => x < 5 ) and bigArray.filter( ( x, idx, arr ) => x < 5 ) are all equivalent.

...well, JavaScript doesn't support function overloading: each function name resolves to a single function implementation, so omitting unused parameters isn't a problem. Now while Rust doesn't support function overloading either, it's still a very large and complex language that has many situations where you will need to explicitly declare a parameter that you don't use (strictly speaking, _ represents an unbound identifier and you cannot use _ as a variable).

The main use-case for naming a function parameter to _ in Rust is because it's a value annotated with the "must_use" attribute - but if you really know you don't need to use that (bound) parameter and you don't want to be bombarded with low-value compiler warnings about must_use values, then _ is a handy solution.

Another use-cases of _ is to declare that a call-site's return-value is being willfully discarded (so this syntax signifies intent), for example:

let _ = someFunctionThatReturnsAValue();

...whereas if you simply put someFunctionThatReturnsAValue(); on its own line then anyone else reading the code, or a static-analysis tool, will think you absent-mindedly forgot to check someFunctionThatReturnsAValue's return-value - but using let _ = ... makes it clear that you really don't care about the return value such that you don't want static-analysis tools dinging you.


So given unwrap_or_else(|_| panic!("Error connecting to {}", database_url)), what does |_| mean?

  • unwrap_or_else is a method of std::result.

  • unwrap_or_else's parameter is a callback function op: FnOnce. If the result is-not-Ok then op will be invoked and op's return-value becomes the end-result of the unwrap_or_else expression (or it panics... your call).

    • Crucially, the op function in unwrap_or_else accepts one (1) parameter which is the E error-value contained within the result.
    • In this case, the panic!("Error connecting to {}", database_url)) expression doesn't use the inner error value at all (which I think is a bad idea) so the callback closure/function discards the value by using the _ syntax.
  • So in conclusion, |_| in unwrap_or_else(|_| panic!("Error") means "The argument of unwrap_or_else is an anonymous function accepting an E (error value)-typed parameter - buuuut we just don't care about it, so pretend it doesn't exist".



Answered By - Dai
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is "<[_]>" in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

In the vec! macro implementation there is this rule:

($($x:expr),+ $(,)?) => (
    $crate::__rust_force_expr!(<[_]>::into_vec(box [$($x),+]))
);

What exactly is that <[_]> in it?


Solution

Breaking down the specific parts of the syntax:

  • <T>::f is the syntax to explicitly call f associated with a type T. Usually just T::f is enough, but pedantically, :: requires a path, which is why it is used here since [_] is not. The <...> allows any type to be used as a path. See Why do I need angle brackets in <$a> when implementing macro based on type?
  • [T] is the type denoting a slice of type T.
  • _ used as a type is a placeholder or "wildcard". It is not a type itself, but serves to indicate that the type should be inferred. See What does it mean to instantiate a Rust generic with an underscore?


Answered By - kmdreko
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does Rust's unary || (parallel pipe) mean?

 December 12, 2022     rust, syntax     No comments   

Issue

In Non-Lexical Lifetimes: Introduction, Niko includes the following snippet:

fn get_default3<'m,K,V:Default>(map: &'m mut HashMap<K,V>,
                                key: K)
                                -> &'m mut V {
    map.entry(key)
       .or_insert_with(|| V::default())
}

What does the || V::default() mean here?


Solution

It is a closure with zero arguments. This is a simplified example to show the basic syntax and usage (play):

fn main() {
    let c = || println!("c called");
    c();
    c();
}

This prints:

c called
c called

Another example from the documentation:

let plus_one = |x: i32| x + 1;

assert_eq!(2, plus_one(1));


Answered By - Arjan
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What do the ampersand '&' and star '*' symbols mean in Rust?

 December 12, 2022     dereference, reference, rust, syntax     No comments   

Issue

Despite thoroughly reading the documentation, I'm rather confused about the meaning of the & and * symbol in Rust, and more generally about what is a Rust reference exactly.

In this example, it seems to be similar to a C++ reference (that is, an address that is automatically dereferenced when used):

fn main() {
    let c: i32 = 5;
    let rc = &c;
    let next = rc + 1;
    println!("{}", next); // 6
}

However, the following code works exactly the same:

fn main() {
    let c: i32 = 5;
    let rc = &c;
    let next = *rc + 1;
    println!("{}", next); // 6
}

Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.

My understanding so far, is that, inserting * in front of a Rust reference dereferences it, but the * is implicitly inserted anyway so you don't need to add it (while in C++, it's implicitly inserted and if you insert it you get a compilation error).

However, something like this doesn't compile:

fn main() {
    let mut c: i32 = 5;
    let mut next: i32 = 0;
    {
        let rc = &mut c;
        next = rc + 1;
    }
    println!("{}", next);
}
error[E0369]: binary operation `+` cannot be applied to type `&mut i32`
 --> src/main.rs:6:16
  |
6 |         next = rc + 1;
  |                ^^^^^^
  |
  = note: this is a reference to a type that `+` can be applied to; you need to dereference this variable once for this operation to work
  = note: an implementation of `std::ops::Add` might be missing for `&mut i32`

But this works:

fn main() {
    let mut c: i32 = 5;
    let mut next: i32 = 0;
    {
        let rc = &mut c;
        next = *rc + 1;
    }
    println!("{}", next);  // 6
}

It seems that implicit dereferencing (a la C++) is correct for immutable references, but not for mutable references. Why is this?


Solution

Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.

A reference in C++ is not the same as a reference in Rust. Rust's references are much closer (in usage, not in semantics) to C++'s pointers. With respect to memory representation, Rust's references often are just a single pointer, while C++'s references are supposed to be alternative names of the same object (and thus have no memory representation).

The difference between C++ pointers and Rust references is that Rust's references are never NULL, never uninitialized and never dangling.


The Add trait is implemented (see the bottom of the doc page) for the following pairs and all other numeric primitives:

  • &i32 + i32
  • i32 + &i32
  • &i32 + &i32

This is just a convenience thing the std-lib developers implemented. The compiler can figure out that a &mut i32 can be used wherever a &i32 can be used, but that doesn't work (yet?) for generics, so the std-lib developers would need to also implement the Add traits for the following combinations (and those for all primitives):

  • &mut i32 + i32
  • i32 + &mut i32
  • &mut i32 + &mut i32
  • &mut i32 + &i32
  • &i32 + &mut i32

As you can see that can get quite out of hand. I'm sure that will go away in the future. Until then, note that it's rather rare to end up with a &mut i32 and trying to use it in a mathematical expression.



Answered By - oli_obk
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is | | symbol in function call?

 December 12, 2022     rust, syntax     No comments   

Issue

While going through rust documentation I found below code

let k = 21;
let x : Result<_, &str> = Ok("foo");
assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);

What exactly is |e| & |v| in last line ? why it is required?


Solution

The .map_or_else functions take a closure as a parameter. A closure is an anonymous function that can optionally capture the environment where they are defined. The syntax to define a closure is

let c = |x| println!(x + 2);

This takes 1 parameters which is mapped to the x variable. Calling c(2) will print 4, calling c(4) will print 6.

Similarly |e| k * 2 and |v| v.len() is also a closure. They also take 1 parameter, e and k which are the parameter names whose values will be filled by the .map_or_else function.



Answered By - Arijit Dey
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does :: (double colon) mean before an identifier?

 December 12, 2022     rust, syntax     No comments   

Issue

This line is from Rust libc crate. What is the use of double colon here? I thought its bringing c_uint in the scope from the crate root but I can't find where its defined in the crate root.

pub type speed_t = ::c_uint;

Solution

https://doc.rust-lang.org/reference/paths.html#path-qualifiers

Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved.

::

Paths starting with :: are considered to be global paths where the segments of the path start being resolved from the crate root. Each identifier in the path must resolve to an item.

So your idea was correct, it is resolving from the crate root.

I can't find where its defined in the crate root.

well libc doesn't in-and-of-itself define anything at the crate root, instead the crate root re-exports the content of the submodule matching the compilation target.

So on unix the "crate root" contains anything exposed by the fixed_width_ints and unix submodules. The former is not really useful for you, but the latter... does define a c_uint symbol.



Answered By - Masklinn
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the ".." syntax inside a struct literal in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

From the std::default::Default docs:

#[derive(Default)]
struct SomeOptions {
    foo: i32,
    bar: f32,
}

fn main() {
    let options = SomeOptions { foo: 42, ..Default::default() };
}

What is the .. prefix doing to the returned value of Default::default() and why is it necessary here? It almost seems like it's acting as a spread operator, but I'm not sure. I understand what ..Default::default() is doing -- filling in the remaining struct parameters with the default values of SomeOptions, but not how .. works. What is the name of this operator?


Solution

This is the struct update syntax. It is "needed" only to have a succinct way of moving / copying all of the members of a struct to a new one, potentially with some small modifications.

The "long" way of writing this would be:

let a = SomeOptions::default();
let options = SomeOptions { foo: 42, bar: a.bar };

You could indeed think of it similar to the JavaScript "spread" operator, but Rust's nuances of ownership and strong typing still come into play, so it's not as widely used. For example, you can't use this syntax to go between values of different types.



Answered By - Shepmaster
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does returning "!" mean in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

Recently I came across a function in Rust that returned ! instead of basic type, like this:

fn my_function() -> ! {
    // ...
}

What does it mean? I was unable to find piece of information about this in The Rust Book. What data does this function return with such indicator?


Solution

It means the function never returns (usually because it unconditionally panics or otherwise ends the program, or because it contains an infinite loop that prevents a return from ever happening).

The appendix describes it as:

! Always empty bottom type for diverging functions

where "diverging" means "never returns".



Answered By - ShadowRanger
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the "()" type in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

As a simple exercise to learn Rust, I've decided to implement a simple binary search:

pub fn binary_search(arr: &[i32], key: i32) -> usize {
    let min: usize = 0;
    let max: usize = arr.len();
    while max >= min {
        let mid: usize = (max - min) / 2 as usize;
        if key == arr[mid] {
            mid as usize
        }

        if key < arr[mid] {
            min = mid + 1;
            continue;
        }

        max = mid - 1;
    }
    -1 as usize
}

#[cfg(test)]
mod tests {
    use super::binary_search;

    #[test]
    fn binary_search_works() {
        let arr: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
        let index: usize = binary_search(&arr, 2);
        assert_eq!(1, index);
    }
}

At build time, I get this error which I do not understand. What is the () type? The variable mid is always usize but even with the as cast I'm getting this compilation error:

error: mismatched types [E0308]
            mid as usize
            ^~~~~~~~~~~~
help: run `rustc --explain E0308` to see a detailed explanation
note: expected type `()`
note:    found type `usize`

Solution

() is the unit type, analogous to a void return type in other languages.

You're getting it here:

if key == arr[mid] {
    mid as usize
}

Rust is expecting that if expression to return (), but you're returning usize for that expression. Since virtually everything in Rust is an expression, you can usually implicit return like you're trying to here, but in this specific case you can't because the if expression is not the only expression in the while expression. You could fix the immediate problem by using return mid as usize; instead.



Answered By - Aurora0001
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the syntax: `instance.method::<SomeThing>()`?

 December 12, 2022     rust, syntax     No comments   

Issue

I read the below syntax from byteorder:

rdr.read_u16::<BigEndian>()

I can't find any documentation which explains the syntax instance.method::<SomeThing>()


Solution

This construct is called turbofish. If you search for this statement, you will discover its definition and its usage.

Although the first edition of The Rust Programming Language is outdated, I feel that this particular section is better than in the second book.

Quoting the second edition:

path::<...>, method::<...>
Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>())

You can use it in any kind of situation where the compiler is not able to deduce the type parameter, e.g.

fn main () {
    let a = (0..255).sum();
    let b = (0..255).sum::<u32>();
    let c: u32 = (0..255).sum();
}

a does not work because it cannot deduce the variable type.
b does work because we specify the type parameter directly with the turbofish syntax.
c does work because we specify the type of c directly.



Answered By - hellow
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does <'_> mean in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

In this code from Debug examples:

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Point")
         .field("x", &self.x)
         .field("y", &self.y)
         .finish()
    }
}

let origin = Point { x: 0, y: 0 };

assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");

What does <'_> mean in f: &mut fmt::Formatter<'_>?


Solution

The ' denotes that it is a Lifetime: https://doc.rust-lang.org/rust-by-example/scope/lifetime.html

This is usually written as 'a where a is the name of the lifetime (like the name of the variable, can be any name)

The _ means that the compiler can infer the name/type. (so you don't have to figure it out, makes it easier) You can find more info here: https://stackoverflow.com/a/37215830/2037998

The <> is because of Generics. You can see that in the docs it is defines as impl<'a> Formatter<'a>



Answered By - Ralph Bisschops
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is Vec<_>?

 December 12, 2022     generics, rust, syntax     No comments   

Issue

I have seen Vec<_> a couple of times already. For example:

let a = "line1\r\nline2\nline3";
println!("{:?}", a.lines().collect::<Vec<_>>());

But what does that 'uncertain face' <_> mean?

I'm used to a typename in angle brackets, but what type can that be? The only meaning of underscore that I'm aware of is from Python as a name for an unused variable.


Solution

It means "Rust compiler, infer what type goes into the Vec". And it is indeed analogous to the unused variable in Python (and in Rust itself), in that it represents a placeholder for a type, like it can represent a placeholder for a variable name.

You can find an explanation in The Rust Programming Language chapter about iterator consumers:

Using a _ will let you provide a partial hint:

let one_to_one_hundred = (1..101).collect::<Vec<_>>(); This says "Collect into a Vec<T>, please, but infer what the T is for me." _ is sometimes called a "type placeholder" for this reason.



Answered By - Paolo Falabella
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What does “&*” do in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

I encountered this block of code while reading documentation from a Rust library:

for (ent, pos, vel) in (&*entities, &mut pos_storage, &vel_storage).join() {
    println!("Processing entity: {:?}", ent);
    *pos += *vel;
}

What does &*entities do here? From what I can tell it’s dereferencing entities and then referencing it again. But why?


Solution

This is an explicit reborrow and it's a common idiom that pops up in Rust from time to time.

  • & in an expression only has one meaning: it takes an expression (which must be a place expression) of type T and borrows a reference to it of type &T.

  • For references, * does the opposite of & -- it takes a reference (&T) and makes a place expression of type T. But * can mean different things with different kinds of pointers, since you can override it by implementing Deref. Because * ties in some compiler magic that automatically dereferences the return value of Deref::deref, you can borrow the result of *, turning it back into a plain reference, by using the & operator.

So &*foo is a way of explicitly reborrowing "any kind of pointer to T" as a &T, and is the equivalent of manually calling Deref::deref(&foo).

(The above explanation also works for &mut borrows -- just replace & with &mut and Deref with DerefMut.)

It's not clear in the example you link what entities is, but it's probably some kind of smart pointer, where the join() method requires a plain reference. For another example where this is required, consider using [&str]::concat to concatenate a String with some &strs:

// I want to concatenate this with some other strings
let s = String::from("Amelia");
// The following won't compile: you can't make an array of &str and String
assert_eq!(["Hello", ", ", s].concat(), "Hello, Amelia");    // WRONG
// However, &*s takes a reference to the str pointed to by s.
assert_eq!(["Hello", ", ", &*s].concat(), "Hello, Amelia");  // OK

See also

  • Is there a difference between slicing and an explicit reborrow when converting Strings to &strs?
  • Box<T> to &T in Rust


Answered By - trent
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the usage of the asterisk symbol in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

I'm new to Rust and I don't understand the following piece of code:

let mut x = 5;
{
    let y = &mut x;
    *y += 1;
}
println!("{}", x);

Explanation from the Rust site:

You'll also notice we added an asterisk (*) in front of y, making it *y, this is because y is a &mut reference. You'll need to use astrisks [sic] to access the contents of a reference as well.

If *y is a reference, why does the following code work

fn main() {
    let mut x = 5;
    {
        let y = &mut x;
        println!("{}", y);
    }
}

I know I'm not modifying the value here, but what is the difference and why would y += 1; not work?


Solution

If *y is a reference

*y is not a reference. y is a reference; *y dereferences y, allowing you access to the referred-to value.

what is the difference [between += and println!]

println! is a macro that automatically references the arguments given to it. In addition, the Display trait (used via {} in the format string) is implemented for all references to types that themselves implement Display (impl<'a, T> Display for &'a T where T: Display + ?Sized).

Thus, println!("{}", y); is actually printing out a reference to a reference to a value. Those intermediate references are automatically dereferenced due to the implementation of Display.

+=, on the other hand, is implemented via the AddAssign trait. The standard library only implements adding an integer type to itself (impl AddAssign<i32> for i32). That means that you have to add an appropriate level of dereferencing in order to get both sides to an integer.



Answered By - Shepmaster
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What exactly does '#[derive(Debug)]' mean in Rust?

 December 12, 2022     rust, syntax     No comments   

Issue

What exactly does #[derive(Debug)] mean? Does it have something to do with 'a? For example:

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

Solution

#[...] is an attribute on struct Person. derive(Debug) asks the compiler to auto-generate a suitable implementation of the Debug trait, which provides the result of {:?} in something like format!("Would the real {:?} please stand up!", Person { name: "John", age: 8 });.

You can see what the compiler did by executing cargo +nightly rustc -- -Zunstable-options --pretty=expanded. In your example, the compiler will add something like

#[automatically_derived]
#[allow(unused_qualifications)]
impl <'a> ::std::fmt::Debug for Person<'a> {
    fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            Person { name: ref __self_0_0, age: ref __self_0_1 } => {
                let mut builder = __arg_0.debug_struct("Person");
                let _ = builder.field("name", &&(*__self_0_0));
                let _ = builder.field("age", &&(*__self_0_1));
                builder.finish()
            }
        }
    }
}

to your code. As such an implementation is suitable for almost all uses, the derive saves you from writing it by hand.

The 'a is a lifetime-parameter for the type Person; that is, there (could be) several versions of Person, each with its own concrete lifetime, which will be named 'a. This lifetime-parameter is used to qualify (generically) the reference in the field name, a reference to some value of type str. This is necessary because the compiler will need some information on how long this reference will be valid (to the ultimate goal that the reference to the value of name does not become invalid while a value of type Person is still in use).



Answered By - user2722968
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing