These are chat archives for rust-lang/rust

1st
Mar 2019
Tom Jakubowski
@tomjakubowski
Mar 01 07:25
is it legal to cast a pointer to T to a pointer to struct Foo<T>(T), and then use it?
aha, #[repr(transparent)]
Tom Jakubowski
@tomjakubowski
Mar 01 07:53
hm, not sure I can rely on that actually
Zakarum
@omni-viral
Mar 01 12:49
#[repr(transparent)] is exactly the thing
Matteo Ferretti
@ZER0
Mar 01 13:18

Hi there! I need a bit of advice. Beside for changing the mutability, when the shadowing is consider a good practice in rust, or idiomatic?
I also have a specific example: a function takes a vector of u8 as parameter, and then it converts in a map of scalar. Without shadowing, would be:

fn foo(bar_u8: Vec<u8>) {
  let bar: Vec<Scalar> = ...;
  ...
}

With the shadowing, I can reuse the same name:

fn foo(bar: Vec<u8>) {
  let bar: Vec<Scalar> = ...;
  ...
}

Now, coming from other language my natural tendency is looking at the shadowing as a source of potential problem or, at least, mislead. However, in Rust, it seems kind of common practice.
Any opinions about that? Thanks!

Sylwester Rąpała
@xoac
Mar 01 13:31

@ZER0 I think the first solution in general is better. Since Rust will error you when u use bar_u8 since it will be probably moved (if it will not be moved and u want protect input bar variable - use second scenario).
And I think it's not rust problem but any lang problem.

This is quite acceptable

fn foo(bar: Vec<u8>) {
  let bar: Vec<Scalar> = ...;
  ...
}

but this will be terrible in any language.

fn foo(bar: Vec<u8>) {
...
...
...
  let bar: Vec<Scalar> = ...;
  ...
}

But it's just my opinion don't take it as rust practice or sth.

Tim Robinson
@1tgr
Mar 01 13:34
I think the shadowing is idiomatic in any language where let works like it does in Rust, it originally derives from ML (I think) via things like OCaml and Haskell
After line 1 you're genuinely not going to use the first bar any more, so why keep it in scope? Better to re-use the bar identifier under a new type to make it clear you're not going to use bar: Vec<u8> from this point onwards
Matteo Ferretti
@ZER0
Mar 01 13:57
@1tgr thanks! I had the same feeling, it's just, you know, years of other languages' habit where shadowing is definitely not safe as it is in Rust. :)
Brian Knapp
@knappador
Mar 01 14:29
72 |     let gpu_window = GpuWindow::new(&picker, &surface)?;
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
In fact, return sig is ) -> Result<GpuWindow, Box<dyn Error>> {
Oh lol, it was complaining about the test's signature
Tom Jakubowski
@tomjakubowski
Mar 01 18:18
@omni-viral thanks for confirming! my reluctance was misplaced (had a bug elsewhere…) :)