Convert string to integer golang11/15/2023 Throwing an exception is obviously a common choice in the modern world, but depending on how the function will be used, any of those could make sense. completely undefined behaviour (no promises - might corrupt memory or crash).an undefined return value (but at least a return value).a well defined best-effort result (converting "123abc" to 123).a special "error" int return that is known to be invalid or highly unlikely in the domain the function is dealing with (e.g.a standard way of marking the absence of a value (null return, "optional"/"maybe" return type, separate return-presence indicator).a standard way of signaling an error (exception, separate status return).A well-written function might promise to handle invalid input with: Likewise, though we don't customarily represent the zero-value with an empty string, it can be a perfectly reasonable choice to declare that this function considers "" a representation of zero. These are really two separate (though not independent) design decisions:Ībout that first decision, any of "+3", "03", "0x3", "3.0", "3.", "3e0", "3 ", " 3" could in some domain reasonably be declared a valid or invalid int representation. Of course it depends on how the function is meant to be used. If you document what your conversion function does, then it will not (or at least should not) surprise the clients of your function. If there are no implementations for your situation, then look at other languages or libraries for inspiration of how to handle those cases in your own implementation. So all in all the actual answer to your question should be to use the string-to-number conversion library functions supplied with your current language and framework, if they have any.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |