Home >Backend Development >Golang >How to Correctly Sleep for Fractions of a Time Duration in Go?
Sleeping by Fractions of a Time Duration
In Go, sleeping for a fraction of a time duration can be achieved using the time.Sleep() function, which takes a time.Duration as its argument. However, when attempting to specify a fraction of a duration, one may encounter different behaviors based on the code structure.
Consider these two scenarios:
// Case 1: Works s := time.Hour / 73.0 fmt.Println("sleeping: ", s) time.Sleep(s) // Case 2: Fails d := 73.0 s := time.Hour / d fmt.Println("sleeping: ", s) time.Sleep(s) // Error: time.Hour / d (mismatched types time.Duration and float64)
In Case 1, the code successfully sleeps for a fraction of an hour, while in Case 2, it fails with a type mismatch error. To understand why, it's crucial to grasp how constants and types are handled in Go.
Understanding Constant Expressions
In Go, constants are strongly typed and can be either untyped (with a default type) or explicitly typed.
In Case 1, time.Hour is a typed constant of type time.Duration. When dividing time.Hour by 73.0, Go automatically converts the untyped constant 73.0 to time.Duration, resulting in the expression time.Hour / time.Duration(73.0).
Inferring Types and Mismatched Types
In Case 2, d is an untyped constant initialized with 73.0. Since a type is required, Go infers the type based on the constant value, resulting in d becoming a float64.
Subsequently, when attempting to divide time.Hour by d, which is now of type float64, Go detects a type mismatch. Division of time.Duration and float64 is not allowed in Go.
Resolving the Type Mismatch
To resolve the type mismatch, one can explicitly convert d to time.Duration before performing the division:
s := time.Hour / time.Duration(d)
Alternatively, d can be defined directly as a time.Duration variable:
d := time.Duration(73.0) s = time.Hour / d
Or, using a type conversion in the variable declaration:
var d time.Duration = 73.0 s = time.Hour / d
Handling Values Unrepresentable by time.Duration
If the division result cannot be represented by time.Duration (e.g., dividing an hour by 73.5), convert time.Hour to float64, perform the division, and then convert the result to time.Duration:
d := 73.5 s := time.Duration(float64(time.Hour) / d)
By understanding the type conversion rules and explicitly handling the conversion if necessary, one can successfully sleep for fractions of a time duration in Go.
The above is the detailed content of How to Correctly Sleep for Fractions of a Time Duration in Go?. For more information, please follow other related articles on the PHP Chinese website!