-1

In Rust, the following code would work:

fn test_slice(slices: &[i32]) {
    println!("{:?}", slices);
}

fn main() {
    let slices:&[i32] = &[1,2,3];
    test_slice(slices);
}

However, why the code below would also work instead of giving type mismatch error?

fn main() {
    let slices:&[i32] = &[1,2,3];
    test_slice(&&&slices);
}
silverwen
  • 287
  • 3
  • 11

1 Answers1

0

I find a reference here: https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/deref-coercions.html#deref-and-method-calls

Looks like Rust would insert as many * as needed automatically to get it right.

silverwen
  • 287
  • 3
  • 11
  • _No, it won't insert `\*`. _ Try this out: ``` let s = String::new(); String::into_bytes(&s); ```` **It won't compile!** – Siiir Jul 28 '23 at 04:28
  • 1
    Inserting `.deref()` or `.deref_mut()` is not the same as inserting `*`. The latter doesn't happen. – Siiir Jul 28 '23 at 04:30
  • 1
    @Siiir `*` calls `deref(_mut)`. The difference with `String` is that it isn't copy, so you can't move it out of dereference of `&String`. You can move non-copy types out of dereference of `Box`, so `String::into_bytes(boxed_string)` would expand to `String::into_bytes(*boxed_string)` and that would compile. – Ivan C Jul 28 '23 at 06:18