Home >Backend Development >Golang >Why Does Dividing Go's `time.Duration` by a Floating-Point Number Sometimes Fail?

Why Does Dividing Go's `time.Duration` by a Floating-Point Number Sometimes Fail?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 02:57:10872browse

Why Does Dividing Go's `time.Duration` by a Floating-Point Number Sometimes Fail?

Sleeping with Floating-Point Duration Fractions

In Go, dividing a time duration by a floating-point value can lead to unexpected behavior. Consider the following example:

This code successfully prints the duration "1m38s12ms" and sleeps the program for that amount of time. However, this code fails:

With the error:

Why do these two codes behave differently?

Type System and Constant Conversion

In the first code, the constant 73.0 is an untyped numeric constant. When used in expressions, Go automatically converts it to the appropriate type based on the context. In this case, time.Hour is of type time.Duration, so 73.0 is converted to time.Duration.

However, in the second code, d is explicitly declared as type float64. When dividing time.Hour by d, Go attempts to perform division between time.Duration and float64, which is not allowed.

Converting to time.Duration

To make the second code work, d must be converted to time.Duration. There are several ways to achieve this:

  1. Explicit Conversion:
  1. Declare d as time.Duration:
  1. Use a type alias:

When converting floating-point values to time.Duration, precision may be lost if the value cannot be represented with int64. In these cases, conversion in the reverse direction may be required:

The above is the detailed content of Why Does Dividing Go's `time.Duration` by a Floating-Point Number Sometimes Fail?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn