简体   繁体   中英

How to generate a random number in vlang?

I want to randomly pick an item in a array.Like javascript code

words[Math.floor(Math.random() * words.length)]

But I don't know how to generate a number like javascript Math.random() function in vlang. Does anyone know ?

Per the documentation at rand , you can use the rand module and for example, the rand.u32n(words.length) function. Make sure you handle the optional case..

There are a few ways

  • use choose
import rand
words := ['one', 'two', 'three']
word := rand.choose<string>(words, 1) or {[words[0]]} // this is a list
println(word[0])
  • use intn
import rand
words := ['one', 'two', 'three']
word := words[rand.intn(words.len) or {0}]
println(word)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM