News for hackers. Stuff that matters.
Re:My Struggles with Rust by erickt on Sunday May 07, 2017 @09:31AM (#14285368)
Hello Justin Turpin! Sorry to hear your struggles with rust. It's always going to be a bit more verbose using rust than Python due to type information, but I think there are some things we could do to simplify your code. Would you be comfortable posting the 20 line code for us to review? I didn't see a link in your post.

Anyway, so some things that could make your script easier:

* for simple scripts I tend to use the `.expect` method if I plan on killing the program if there is an error. It's just like unwrap, but it will print out a custom error message. So you could write something like this to get a file:

    let mut file = File::open("conf.json")
        .expect("could not open file");
(Aside: I never liked the method name `expect` for this, but is too late to do anything about that now).

* next, you don't have to create a struct for serde if you don't want to. serde_derive is definitely cool and magical, but it can be too magical for one off scripts. Instead you could use serde_jaon::Value [0], which is roughly equivalent to when python's json parser would produce. * next, serde_json has a function called from from_reader [1], which you can use to parse directly from a `Read` type. So combined with Value you would get:

    let config: Value = serde::from_reader(file)
        .expect("config has invalid json");
* Next you could get the config values out with some methods on Value:

    let jenkins_server = config.get("jenkins_server")
        .expect("jenkins_server key not in config")
        .as_str()
        .expect("jenkins_server key is not a string");
There might be some other things we could simplify. Just let us know how to help.

[0]: https://docs.serde.rs/serde_json/enum.Value.html

[1] https://docs.serde.rs/serde_json/de/fn.from_reader.html

Re:My Struggles with Rust by eriknstr on Sunday May 07, 2017 @10:09AM (#14285524)
While it's too late to change the name "expect", could one create an alias for it and call it say, "on_error"?
Re:My Struggles with Rust by eximius on Sunday May 07, 2017 @11:25AM (#14285877)
I'd expect 'on_error' to take a function as a callback, not a string. But yes, a better named function could be added
Re:My Struggles with Rust by skybrian on Sunday May 07, 2017 @12:12PM (#14286114)
Perhaps or_die, similar to Perl?
Re:My Struggles with Rust by sanderjd on Sunday May 07, 2017 @06:00PM (#14287938)
Yep, this is what I always wanted it to be! But maybe or_panic would be better. Naming things is hard.
Re:My Struggles with Rust by allan_s on Tuesday May 09, 2017 @04:07PM (#14303384)
or_fail_with("") ?
Re:My Struggles with Rust by eternalban on Sunday May 07, 2017 @03:31PM (#14287131)
expect[ing_error]("could not open the file")
Re:My Struggles with Rust by rootlocus on Sunday May 07, 2017 @04:16PM (#14287385)
You're not expecting an error. On the contrary, you're expecting a value or throwing an error.
Re:My Struggles with Rust by eternalban on Tuesday May 09, 2017 @08:32AM (#14299425)
You're expecting specific errors.
Re:My Struggles with Rust by edmccard on Sunday May 07, 2017 @08:14PM (#14288430)
In my Rust crates, I use a custom trait[1], with implementations for Option and Result, that provides an expected() method which, if it panics, prefixes the message with "expected: ". So you can write

  foo().pop().expected("foo length >= 1");
and if it fails, the error is something like "panicked at 'expected foo length >= 1'".

[1]https://gist.github.com/edmccard/8898dd397eec0ff3595c28ada52...

Re:My Struggles with Rust by dleslie on Sunday May 07, 2017 @03:59PM (#14287285)
A failed expectation for one user isn't always an error for other users; calling out on_error may confuse people because it indicates an error may occur and must be handled.
Re:My Struggles with Rust by IshKebab on Sunday May 07, 2017 @02:04PM (#14286624)
Or `unwrap_msg()`?
Re:My Struggles with Rust by GolDDranks on Sunday May 07, 2017 @10:19AM (#14285574)
If I know that the unwrap is 100% safe I tend to write: `.expect("Invariant: $REASON_WHY_THIS_NEVER_FAILS")`
Re:My Struggles with Rust by gnuvince on Sunday May 07, 2017 @06:51PM (#14288157)
Cool trick!
Re:My Struggles with Rust by huntie on Sunday May 07, 2017 @12:22PM (#14286154)
It might be easier to do:

  let config: HashMap<String, String> = serde_json::from_reader(file)
      .expect("config has invalid json");
This means that you can just do

  let jenkins_server = config.get("jenkins_server")
      .expect("jenkins_server key not in config");
Re:My Struggles with Rust by QuercusMax on Sunday May 07, 2017 @09:57AM (#14285463)
Was the expect method​ supposed to be named except, as in exception? That would make a lot more sense.
Re:My Struggles with Rust by erickt on Sunday May 07, 2017 @10:29AM (#14285619)
If I recall correctly we just couldn't come up with a great name for it. To me "expect" is a positive action, but the argument is about it failing to meet the expectation. Semantically I like `thing.unwrap_or(|| panic!("failure message"))`. It feels more like what I would want to say, but it just is so wordy.

Ultimately I'm happy we just picked something and moved on, but still mildly annoys me whenever I write it. If only we found that perfect method name way back when...

Re:My Struggles with Rust by Double_Cast on Sunday May 07, 2017 @12:10PM (#14286106)

  .beware("could not open file");
Re:My Struggles with Rust by tomjakubowski on Sunday May 07, 2017 @07:03PM (#14288193)

    .be_wary_of("but hole")
Re:My Struggles with Rust by AlphaSite on Sunday May 07, 2017 @10:43AM (#14285688)
The java optional api uses orElseThrow which I think is quite clear.
Re:My Struggles with Rust by bluejekyll on Sunday May 07, 2017 @10:53AM (#14285734)
Agreed, I've never liked 'expect' either; 'or_else_panic(msg)' would be much clearer

Edit: 'or_panic(msg)' would be shorter and also good.

Re:My Struggles with Rust by erickt on Sunday May 07, 2017 @11:06AM (#14285788)
I think that was one of the proposed variations, but we ended up picking the shorter .expect to cut down on repetition. We expected (ha) that this function would be used in these one-offs, so we wanted something more efficient.
Re:My Struggles with Rust by bluejekyll on Sunday May 07, 2017 @11:20AM (#14285859)
As an old Java hack, my allowance for repetition is high. Especially when using and IDE that basically writes the code for me ;)
Re:My Struggles with Rust by e12e on Sunday May 07, 2017 @11:35AM (#14285928)
otherwise(msg)?
Re:My Struggles with Rust by MaxGabriel on Sunday May 07, 2017 @11:44AM (#14285987)
I would expect such a function to provide a default value
Re:My Struggles with Rust by e12e on Sunday May 07, 2017 @12:21PM (#14286151)
I actually initially had it as sort of a callback:

.otherwise(panic(msg))

(although I assume a rust panic! isn't really a function call).

But isn't the way to get the default, simply to use unwrap()?

In a simple script, failing to open a configuration file for reading is likely a show stopper, and you probably want to log/print an error (no such file, wrong permission, etc).

But in, say, a paint program, you'd normally not want to panic and crash if the image file a user selected to open in a file dialog is invalid or went away between the click-to-select and the click-to-open. In such a program you'd want to handle most file errors much more defensively.

Re:My Struggles with Rust by AsyncAwait on Sunday May 07, 2017 @10:55AM (#14285738)
It is, but also quite long, which I do not think suits Rust naming conventions.
Re:My Struggles with Rust by bluejekyll on Sunday May 07, 2017 @11:27AM (#14285889)
Not really though: 'unwrap_or_else' is of similar length.
Re:My Struggles with Rust by Pxtl on Sunday May 07, 2017 @10:09AM (#14285525)
Not a Rust guy, but it looks like a way to say "this option value is required and if it is not present, crash with the following error". So "expect" is a fair name, since it means a value is expected and the absence of a value is unexpected.

I could see "required" or "require" as a better name. Or even just break the "positive names" rule and go with "notOptional".

Re:My Struggles with Rust by eriknstr on Sunday May 07, 2017 @10:14AM (#14285543)
Looking at it that way, I think it's possible to make "expect" more comfortable to read by how you phrase your error messages.

Instead of

    let mut file = File::open("conf.json")
        .expect("could not open file");
and

    let config: Value = serde::from_reader(file)
        .expect("config has invalid json");
and

    let jenkins_server = config.get("jenkins_server")
        .expect("jenkins_server key not in config")
        .as_str()
        .expect("jenkins_server key is not a string");
One could write

    let mut file = File::open("conf.json")
        .expect("Need to be able to open file `conf.json'.");
and

    let config: Value = serde::from_reader(file)
        .expect("The file `conf.json' must contain valid JSON.");
and

    let jenkins_server = config.get("jenkins_server")
        .expect("The config must have a key named `jenkins_server'.")
        .as_str()
        .expect("The config value of `jenkins_server' must be a string.");
Something like that.
Re:My Struggles with Rust by erickt on Sunday May 07, 2017 @10:31AM (#14285632)
That is a good point. I'm going to have to start being more positive in my expectations :)
Re:My Struggles with Rust by swsieber on Sunday May 07, 2017 @10:20AM (#14285581)
I think it's like Assert. You pass an error message the same way you pass an error message to assert.
Re:My Struggles with Rust by bpicolo on Sunday May 07, 2017 @10:53AM (#14285732)
4 chained function calls from config -> read a key from it is quite an ask. Though I realize there's reason for it. There are many cases I'd be happy to have panics occur for invariants. config.strictString('foo') or something of that nature seems like it could be a more ergonomic choice in cases like thise.
Re:My Struggles with Rust by bluejekyll on Sunday May 07, 2017 @10:58AM (#14285758)
What he is showing is how someone who knows Rust well, would potentially approach this problem.

What you're point out is that it's a large bar to ask a new comer to the language to do this because it requires a deeper understanding of the language to use.

Is it not appropriate to show that you can reduce the complexity of a program by using other features of the language?

It's not significantly different from reducing

   x + x + x + x
To

   4x
Re:My Struggles with Rust by jackcviers3 on Sunday May 07, 2017 @11:05AM (#14285782)
Each function call is a transformation on the previous argument. Whether or not you assign the results to a variable first before calling the second doesn't change the behavior of the code.

But yes, it does appear that the config library needs an extra wrapper that loads from files and returns configs (in a context) that does the common work for you.

Re:My Struggles with Rust by MikkoFinell on Sunday May 07, 2017 @01:09PM (#14286357)
I cant even opt out of using exceptions? Good thing I didn't waste my time with this lang.
Re:My Struggles with Rust by sanderjd on Sunday May 07, 2017 @06:14PM (#14288010)
You may have confused the method "expect" as being "except", as in "exception". That's not what it means - it means to "panic" with the given string as the error message. Panics in Rust have some similarities to exceptions in C++, but are not the same thing.
Re:My Struggles with Rust by caconym_ on Sunday May 07, 2017 @01:41PM (#14286506)
Exceptions don't exist in Rust.
Re:My Struggles with Rust by guipsp on Sunday May 07, 2017 @01:27PM (#14286442)
expect is panic, not an exception