Multiplying Durations in Go
In Go, when attempting to multiply a duration by an integer, developers may encounter the error: "invalid operation: int32 and time.Duration (mismatched types int32 and time.Duration)." This error stems from the fact that int32 and time.Duration are different types.
To resolve this issue, it is necessary to convert the int32 to a time.Duration before performing the multiplication. This conversion can be achieved using the following syntax:
time.Duration(rand.Int31n(1000)) * time.Millisecond
In this example, the rand.Int31n function returns an int32 representing a random number up to the specified limit (in this case, 1000). By converting this int32 to a time.Duration using the time.Duration type conversion, we can then multiply by the desired unit of duration (in this case, milliseconds using the time.Millisecond constant).
By following this approach, developers can successfully multiply durations by integers in Go and avoid the aforementioned error.
The above is the detailed content of How to Multiply a Duration by an Integer in Go?. For more information, please follow other related articles on the PHP Chinese website!