From fe97a6748d106e9edaeeec5b6a9b7c2d451bbdb1 Mon Sep 17 00:00:00 2001 From: devlights Date: Wed, 14 Aug 2024 15:44:17 +0000 Subject: [PATCH] Add string_random_string example --- examples/basic/strs/README.md | 1 + examples/basic/strs/examples.go | 1 + examples/basic/strs/random_string.go | 46 ++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 examples/basic/strs/random_string.go diff --git a/examples/basic/strs/README.md b/examples/basic/strs/README.md index e0900e9e..d1475ad0 100644 --- a/examples/basic/strs/README.md +++ b/examples/basic/strs/README.md @@ -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 | 指定された文字数のランダム文字列を作成するサンプルです. | diff --git a/examples/basic/strs/examples.go b/examples/basic/strs/examples.go index 53bdaf37..73df3bbd 100644 --- a/examples/basic/strs/examples.go +++ b/examples/basic/strs/examples.go @@ -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 } diff --git a/examples/basic/strs/random_string.go b/examples/basic/strs/random_string.go new file mode 100644 index 00000000..0b1dbcbf --- /dev/null +++ b/examples/basic/strs/random_string.go @@ -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 + */ +}