1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-08 06:32:28 +08:00

[feature]<slice>: support random item (#146)

Signed-off-by: o98k-ok <hggend@gmail.com>
This commit is contained in:
o98k
2023-11-22 16:51:37 +08:00
committed by GitHub
parent 31c618c187
commit 3802c715c3
5 changed files with 109 additions and 0 deletions

View File

@@ -2488,4 +2488,35 @@ func main() {
// [[2 4] [1 3 5]]
// [[1 2] [3 4] [5]]
}
```
### <span id="Random">Random</span>
<p>随机返回切片中元素以及下标, 当切片长度为0时返回下标-1</p>
<b>函数签名:</b>
```go
func Random[T any](slice []T) (val T, idx int)
```
<b>示例:<span style="float:right;display:inline-block;">[运行](TODO)</span></b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
nums := []int{1, 2, 3, 4, 5}
val, idx := slice.Random(nums)
if idx >= 0 && idx < len(nums) && slice.Contain(nums, val) {
fmt.Println("okk")
}
// Output:
// okk
}
```