Skip to content

Commit 3cefe69

Browse files
committed
crypto/rand: add and update examples
Change-Id: I77406c22b82c9f8bc57323c783f63c4897486e7e Reviewed-on: https://go-review.googlesource.com/c/go/+/665096 Reviewed-by: Daniel McCarney <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Dmitri Shuralyov <[email protected]> Reviewed-by: Roland Shoemaker <[email protected]>
1 parent ae5a513 commit 3cefe69

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/crypto/rand/example_test.go

+19-5
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,30 @@ import (
1212

1313
// ExampleInt prints a single cryptographically secure pseudorandom number between 0 and 99 inclusive.
1414
func ExampleInt() {
15-
a, err := rand.Int(rand.Reader, big.NewInt(100))
16-
if err != nil {
17-
fmt.Println("error:", err)
18-
return
19-
}
15+
// Int cannot return an error when using rand.Reader.
16+
a, _ := rand.Int(rand.Reader, big.NewInt(100))
2017
fmt.Println(a.Int64())
2118
}
2219

20+
// ExamplePrime prints a cryptographically secure pseudorandom 64 bit prime number.
21+
func ExamplePrime() {
22+
// Prime cannot return an error when using rand.Reader and bits >= 2.
23+
a, _ := rand.Prime(rand.Reader, 64)
24+
fmt.Println(a.Int64())
25+
}
26+
27+
// ExampleRead prints a cryptographically secure pseudorandom 32 byte key.
2328
func ExampleRead() {
2429
// Note that no error handling is necessary, as Read always succeeds.
2530
key := make([]byte, 32)
2631
rand.Read(key)
32+
// The key can contain any byte value, print the key in hex.
33+
fmt.Printf("% x\n", key)
34+
}
35+
36+
// ExampleText prints a random key encoded in base32.
37+
func ExampleText() {
38+
key := rand.Text()
39+
// The key is base32 and safe to display.
40+
fmt.Println(key)
2741
}

0 commit comments

Comments
 (0)