![]() If you do happen to find yourself still using the math/rand package in other parts of your application, it might be worth considering either moving some of that code into a function in your new rand package so that it is easier to reuse and test in isolation. ![]() It might seem odd to wrap another package with the same package name, but in my experience (and in others’ experience) this pattern works well when you want to wrap a package based on the context of what you are building, or if you want to isolate some details that just aren’t relevant to the rest of your application. That way the rest of our code doesn’t need to concern itself with the implementation details of generating random strings, but can instead simply call functions like rand.String(10) to get a random string with 10 characters in it. What this means is we are going to create a custom package named rand that will utilize the functionality provided by the math/rand package in order to create our own functions, and mask most of the implementation details. String() - this function will only take in a length, and will use a default characters set to generate a random string.StringWithCharset() - this function will take in a character set and a length and will generate a random string using that character set.To do this, we will write a short rand package that wraps the math/rand package and provides the following two functions: In this post are we going to cover how to create a function that will allow us to generate random strings of any length in our Go code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |