Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Threep
Apr 1, 2006

It's kind of a long story.

Minus Pants posted:

I'm writing an app that does some basic network performance tests, and I'd like to be able to format some types from std in my print calls (e.g. std::net::SocketAddr). I stumbled around trying to implement the Display trait, which doesn't work because it's an external type. What's the idiomatic way to handle this? Make a wrapper type? Formatter function?

Edit: It looks like I can't use a type alias - same error about an external crate. Do I need to make a type with a SockAddr field and getters/setters? That seems a bit ugly.
I usually make thin wrappers that only implement Display and just create them in the print call:

code:
println!("{}", SockAddrFormatter(&addr));

Adbot
ADBOT LOVES YOU

Threep
Apr 1, 2006

It's kind of a long story.

gonadic io posted:

Just `x >> 8` does that, no? Rust u32's shr fills with zeroes.
You can also do this which compiles down to the same shift:
code:
    let [r, g, b, _a] = rgba.to_be_bytes();
    u32::from_be_bytes([0, r, g, b])

Threep
Apr 1, 2006

It's kind of a long story.
As far as I can tell you're running into the common issue where if let has a funky scope and even though you're returning from inside it, its borrow lasts until the outer scope ends.

If that's the case one of the workarounds is to put the whole if let inside its own scope to force the borrow to be released.

One of my least favourite rust constructs is the suggested workaround if your if let returns an owned/Copy item:

code:
if let Some(num) = { let value = map.get(key); value } {
    return value;
}

Yes that temporary binding is necessary.

Threep fucked around with this message at 17:08 on Jul 4, 2023

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply