You should use some other construct if it's being provided by an external input, even one that you expect to always be valid. a string from another part of your program that is guarenteed to contain a valid value. Using it as in your first example is a bug waiting to happen unless octet is, e.g. Let’s first install it sudo aptitude install pwgen generating random passwords with pwgen is easy, just run pwgen and it will generate a list of passwords for you. my goto tool to generate a random password is pwgen. You should essentially never use it, unless you are absolutely certain that the value you're using it on is definitely an Ok or equivalent. Pwgen Now while making truly random passwords is easy if you have the right tools, remembering them is hard. OTOH, unwrap will panic on failure, unwinding and terminating the entire containing thread, and possibly the entire program depending on compilation settings. (I don't know if using it inside an assignment like your second example will actually work because of that, since you can't put a return there synatically.) This requires that the function you're using it in has a return type of Result with appropriate types. expect ("more detailed panic message") still might be better.įundamentally, ? will immediately end the containing function and return Err on failure, as though you'd manually written return Err(_). The top-level main function of a program is the only other place I'd say using unwrap is alright - though its more verbose equivalent. As for your question: you can use ? anywhere, as long as every function that can fail returns a Result. In general, you only ever want to use unwrap if you've previously verified that it will never fail. With unwrap, you don't give the user of the function that choice - it unconditionally exits the program when you have the error condition. The main difference is that ? is easily recoverable from a higher function - each function in the chain has the possibility to handle the error in a way besides just propagating up. While xxx.unwrap() is approximately: match xxx ", e),Īs you can see, both of them give you the "value" inside, and both short-cut and leave the current function. You can use ? whenever you are inside a function returning the right type of Result (most generally, a Result>).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |