HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to multiply duration by integer?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
durationintegerhowmultiply

Problem

To test concurrent goroutines, I added a line to a function to make it take a random time to return (up to one second)

time.Sleep(rand.Int31n(1000) * time.Millisecond)


However when I compiled, I got this error


.\crawler.go:49: invalid operation: rand.Int31n(1000) * time.Millisecond (mismatched types int32 and time.Duration)

Any ideas? How can I multiply a duration?

Solution

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration:

time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)

Code Snippets

time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)

Context

Stack Overflow Q#17573190, score: 770

Revisions (0)

No revisions yet.