« first day (2103 days earlier)      last day (1400 days later) » 

6:25 AM
What would be the "best practice" in the following case: I'm implementing a Vector3 type and I'm looking at vector normalization. Consider the impl. below:
impl Normal for Vector3 {
    fn normal(&self) -> Result<Self, &str> {
        let len = self.length();
        if !len.is_normal() {
            return Err("Vector length is nan/inf/zero/subnormal");
        }
        Ok(*self * (1_f32 / len))
    }

    fn normalize(&mut self) {
        *self = self.normal().unwrap()
    }
}
For those unfamiliar or... ahem, rusty, a vector must be divided by its length to be normalized. But this length can be anything, including zero.
So, it can fail, hence why I'm returning a Result<Self, &str> on the normal(&self) method. (BTW, if you see something that should be done differently there, let me know.)
However, the normalize(&mut self) method does not return anything (the relationship is similar to ops::Add and ops::AddAssign), but it can fail as well.
What should I do there? Should normalize(&mut self) cause a panic!? It can't return a Result<T, E>, so what should I do?
Should it be made to return a Result<T, E>, even though it doesn't really "return" anything? If so, what would you suggest the method signature should look like?
BTW, this is a library, not a binary.
If you'd like to suggest more changes, I'd welcome that kind of "code review" as well, with the rationale behind the suggestion, but note that is not really in-scope. I don't ask that as a posted question, b/c this is all opinion-based stuff anyway.
 
7:09 AM
```
fn normalize(&mut self) -> Result<(), &str> {
*self = self.normal()?;
Ok(())
}
```
Can do something like this
@code_dredd
so whenever you run this, you check with the enum
 
So you're suggesting changing the signature for a method that doesn't really "return" anything (since normalize() is meant to modify self)? While I realize that's one option that could be implemented, why should it be? Ideally, the method should be able to retain its current signature, right? So, what's the common Rust practice when dealing with this kind of situation (e.g. in the standard lib)?
Assuming the std lib is a good reference point, since I'm still new to Rust. (I've been using it for the last few months here and there.)
 
Technically you are still returning void, consider the option enum
`enum Option<T> {
Some(T),
None,
}
`
That's how rust prevents the usage of null in its code, so when you are unsure that a value _may_ return or not, you change the signature to
`fn name(args...) -> Option<T>`
Same is with the Result enum but here you use it to manage values that may throw errors or that are Ok
https://doc.rust-lang.org/std/result/enum.Result.html
oh I really forgot the chat's markdown scheme eh?
So here you can do a Result<(), T> that means the enumeration is void when its Ok or then its T when its not ok
rust enums are powerful, love them!!
 
@weegee For inline code, I just use the backticks ` and for multi-line code, I post a separate message and hit the "Fixed font" button on the right (if on desktop; don't recall where it shows up in mobile). Haven't had consistent good luck when posting multi-line code along with a message, etc.
W.R.T. the Option<T> vs Result<T, E> types being returned, in what cases is it generally recommended that you return a Result over an Option and viceversa? Is it just a matter of preference, or is there some kind of more fundamental guideline that might push you in a given direction here?
Technically, I could return None on a normal() vector that fails to generate an actual normal vector (e.g. if it has zero length), or I could return an Err(...). Not sure why I should pick one over the other?
(Or I could panic!, but from what I've read in the docs, it's generally not recommended that this be done inside library code, so that the client has the ability to choose what/how to handle it.)
 
7:27 AM
Yes, you decide what's best for you, if you want to return a None variant sure but you can also return an error so users who are using your library know what went wrong with the code, You can have an error struct at T in Result<(), T> to add multiple errors and for panic, make sure to be wise doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html
hmmm got it, you press ctrl + k
 
Yes, I'm familiar with that link.
Thanks for the help. I'll try a few things out and see how it goes.
@weegee
 
8:23 AM
@code_dredd at least there are two paths you could take: 1. fn normalise(&mut self) -> Result<(), ...>, in which case you indicate that the Ok variant could be safely ignored, or 2. fn normalised(self) -> Result<Self, ...> in which case you're leveraging the moving semantics of Rust, consume the previous one and return as a normalised version
 
Well, the borrow checker doesn't like this, but I'm not quite sure why that is. I tried these implementations:
fn normalize(&mut self) -> Result<(), &str> {
    // the "obvious" approach
    *self = self.normal()?;
    Ok(())
}

fn normalize(&mut self) -> Result<(), &str> {
    // trying to limit the scope of the borrow
    // to the inner block (assuming self.normal() is to blame)
    let normal: Self;
    {
        normal = self.normal()?;
    }
    *self = normal;
    Ok(())
}
In both cases, I get: `error[E0506]: cannot assign to *self because it is borrowed`. Using `rustc --explain E0506` provides obvious examples, but I'm not sure this one is obvious to me. For example, while I'd expect `self.normal()` to borrow `self` (given that it's signature literally includes `normal(&self)` in it, I'm not sure *why* it'd keep saying that it's still borrowed after the method returns and it's time to assign the returned object back to `*self`?

What am I missing here? ¯\(°_o)/¯
@PeterVaro Let me process your message for a moment. Loading ...
 
(You could also panic, but in that case I would create two methods: fn normalise() and fn try_normalise() -> Result<..., ...> in which case the first can panic, the second one must not)
 
@PeterVaro If I go with option #1 of fn normalizeZ(&mut self) -> Result<(), ...> I'd still need to call unwrap or expect, right?
"Safely ignore" doesn't not mean that it'd be automatically correct to write:
let mut v = Vector3::from(...);
v.normalize();
// ...
 
Well, likely you would use ?
 
Oh ok, so just write v.normalize()?; and keep going without worrying about Ok(...)
?
 
8:29 AM
Yup
 
That is the common way. In some cases, you may also introduce additional context to the error by mapping it.
 
> "you may also introduce additional context to the error by mapping it"

Can you explain what you mean by that?
 
E.g. v.normalize().map_err(|e| SomeError::NoWay(e))?;
Or something better, of course. The point is that instead of just a reason why the normalization failed, you also get the context around the place where you tried to normalize the vector.
 
What does mapping it that way accomplish? When ? comes into play, what gets extracted is of type SomeError::NoWay which wraps e, right?
Any reason to not just say .expect("yeah, normalize, but nah!...") or something similar instead?
 
Those are different things.
Remember that errors will often float all the way to the top of your library's API calls. If you stick to raising that error to the top, the user of your library will only see something about a normalization failing, but that may be insufficient to understand what went wrong.
In something like a parser, this could be the difference between the user seeing PrematureEndOfFile and MissingRequiredDataElement(PrematureEndOfFile).
 
8:34 AM
Oh yes, forget about my 2nd question there. I derped.
W.r.t. your 1st mapping thing, it seems like creating enums for specific errors would be a good practice for things like these?
 
Very often module/crate-level error types are enums.
 
So, if something fails, you map the error over to the specific enum you want?
ok
 
@code_dredd Just to one which may provide additional context. It is up to you to analyse whether this context is important.
 
So, it could look something like: v.normalize().map_err(|e| VectorError::CannotNormalize(e))?; or something along those lines, if I understand correctly.
 
If e does not describe the fact that a normalization failed, then yes. A closure is not even needed in this case. v.normalize().map_err(VectorError::CannotNormalize)?
 
8:44 AM
@code_dredd I wouldn't worry about the map_err functionality here -- you are the owner of this module, create a proper module level error enum
Maybe further down the line, your other modules and/or crates which use your vector module should use map_err if they don't want to "wrap" your error
 
Ok. Thanks a lot for the help. (The module is a port of a separate system, mostly for self-learning purposes, so, at this time I don't expect anyone else to be impacted.)
 
9:03 AM
@code_dredd I would also think about option 2, that I described above, because that would make your vector chainable! E.g. my_vec.normalise()?.do_something_else();
 
 
1 hour later…
11:06 AM
Ha, I've run into some situations where more experienced people told me "You'd need const generics for that". That looks amazing!
My first thought while looking at the array_chunks() example was "How does it know that it's supposed to be split in chunks of two or three ... oh!"
 
 
6 hours later…
5:11 PM
Is there something innacurate here? Or are people choosing this one as a target of revenge?
 
5:35 PM
@E_net4thecynicalcurator I can't comment on the accuracy, but did you receive those downvotes today, it mentions 1 upvote and 2 downvotes?
 
 
2 hours later…
7:41 PM
@Jason One of them was.
 
8:23 PM
@E_net4thecynicalcurator I don't understand why someone would do that, but I've made it neutral with my limited powers :-)
 
 
3 hours later…
11:03 PM
Well, people are complicated. The more we contribute, the more potential harm we're exposed to.
 
11:34 PM
@E_net4thecynicalcurator you finally starting to understand why I say it's impossible to not offence anyone
I didn't look closely to your answer I tired but
maybe people downvote because they compare it to mathieu lot upvoted answer
 

« first day (2103 days earlier)      last day (1400 days later) »