charSet<\/strong> contains non-ASCII character. <\/p>\n\n\n\nIn Golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other characters are between 1 to 4 bytes. Due to this it is not possible to index a character in a string. In GO, rune data type represents a Unicode point. Once a string is converted to an array of rune then it is possible to index a character in that array of rune. <\/p>\n\n\n\n
So in case, the character set contains some characters that are not ASCII they might occupy more than 1 bytes. In that case, we cannot use the above code to generate a random string as we cannot index into the charSet. For this case, we have to first convert a string into a rune array so that we can index into the rune array to the character and then incrementally form the random string. <\/p>\n\n\n\n
As in the below example, our charSet contains a non-ASCII character '\u00a3'. <\/strong>This character occupies two bytes<\/p>\n\n\n\npackage main\n\nimport (\n \"fmt\"\n \"math\/rand\"\n \"strings\"\n \"time\"\n)\n\nfunc main() {\n rand.Seed(time.Now().Unix())\n \/\/Only lowercase and \u00a3\n charSet := []rune(\"abcdedfghijklmnopqrst\u00a3\")\n var output strings.Builder\n length := 10\n for i := 0; i < length; i++ {\n random := rand.Intn(len(charSet))\n randomChar := charSet[random]\n output.WriteRune(randomChar)\n }\n fmt.Println(output.String())\n output.Reset()\n \n \/\/Lowercase and Uppercase Both and \u00a3\n charSet = []rune(\"abcdedfghijklmnopqrstABCDEFGHIJKLMNOP\u00a3\")\n length = 20\n for i := 0; i < length; i++ {\n random := rand.Intn(len(charSet))\n randomChar := charSet[random]\n output.WriteRune(randomChar)\n }\n fmt.Println(output.String())\n}<\/code><\/pre>\n\n\n\nOutput<\/strong>:<\/p>\n\n\n\nBelow is the output on my machine. On yours it might give a different output<\/p>\n\n\n\n
aidqpbse\u00a3j\nrebhjblsePsLpGBPOhfB<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"Table of Contents OverviewCode Overview ‘mat\/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[3,4,248,149],"class_list":["post-1947","post","type-post","status-publish","format-standard","hentry","category-tech","tag-go","tag-golang","tag-random","tag-string"],"yoast_head":"\n
Generate a random string in Go (Golang) - Welcome To Golang By Example<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n