从切片中选择随机值并在cli上打印

How to pick the random value from slice in golang and i need to display it to cli.I have string which i converted to string array by splitting it. Now i want to choose random string from string array and display to user in cli and i need to ask user to input that particular string which is displayed on screen and compare the user entered input.

 string randgen := ‘na gd tg er dd wq ff  gen  vf ws’
 s:= String.split(randgen,””)
 s = [“na”, “gd”, ”er”, “tg”, “er”, “dd”, “wq”, “ff”, “gen”, “vf”, “ws”]

There are some issues with your code. You shouldn't define the type when initializing a variable using :=.

Also, it's not recommended to depend on spaces to construct and split your slice, as it's not clear what will happen if for example you have multiple spaces, or a tab between the characters instead.

This is a minimal solution that 'just works'.

package main

import (
        "fmt"
        "math/rand"
        "strings"
        "time"
)

func main() {
        randgen := `na gd tg er dd wq ff gen vf ws`
        s := strings.Split(randgen, " ")
        fmt.Println(s)

        rand.Seed(time.Now().UnixNano())
        randIdx := rand.Intn(len(s))

        fmt.Println("Randomly selected slice value : ", s[randIdx])
}

I would suggest reading the rand package documentation for an explanation of what rand.Seed does. Also, take a look at the shuffle function available in rand, as it's suited to your problem, if you want to build a more robust solution.