Skip to content

Commit

Permalink
Merge pull request #842 from devlights/add-randomstring-example
Browse files Browse the repository at this point in the history
  • Loading branch information
devlights authored Aug 14, 2024
2 parents ae70df9 + fe97a67 commit c9ad25b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/basic/strs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
| diff_trimright_trimsuffix.go | string_diff_trimright_trimsuffix | strings.TrimRight と strings.TrimSuffix のちょっとした違いについてのサンプルです. |
| using_string_clone.go | string_using_clone | Go 1.18 で追加された strings.Clone() のサンプルです |
| trimspace.go | string_trim_space | strings.TrimSpace() のサンプルです. |
| random_string.go | string_random_string | 指定された文字数のランダム文字列を作成するサンプルです. |
1 change: 1 addition & 0 deletions examples/basic/strs/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
m["string_cut_prefix_suffix"] = CutPrefixSuffix
m["string_using_clone"] = UsingStringsClone
m["string_trim_space"] = TrimSpace
m["string_random_string"] = RandomString
}
46 changes: 46 additions & 0 deletions examples/basic/strs/random_string.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package strs

import (
"math/rand"
"time"

"github.com/devlights/gomy/output"
)

// RandomString は、指定された文字数のランダム文字列を作成するサンプルです.
//
// # REFERENCES
// - https://gist.github.com/devlights/7534500bfe62c566bf944553ae8974e8
func RandomString() error {
const (
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)

var (
buf = make([]byte, 1<<6)
unixNano = time.Now().UnixNano()
rndSource = rand.NewSource(unixNano)
rnd = rand.New(rndSource)
)

for i := range buf {
buf[i] = charset[rnd.Intn(len(charset))]
}

output.Stdoutl("[output]", string(buf))

return nil

/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: string_random_string
[Name] "string_random_string"
[output] 0OWayZgY57QSJKHvAl8ePRtFSFGtgKJRug6OFdN3XL17oxUW2pqmCaGpGqYV2oEY
[Elapsed] 28.55µs
*/
}

0 comments on commit c9ad25b

Please sign in to comment.