To multiply the duration by an integer in Go, you can convert an integer to duration type using the time.Duration and then multiply it using the operator *.
In Go, you can multiply variables of the same type, so you need to have both parts of the expression of the same type. The simplest thing you can do is cast an integer to duration before multiplying.
Example 1
package main
import (
"fmt"
"time"
)
func main() {
duration := 5 * time.Second
multiplier := 10
result := duration * time.Duration(multiplier)
fmt.Println(result)
}
Output
50s
In this example, we multiply a duration of 5 seconds by an integer of 10 to get a result of 50 seconds. The time.Duration type is used to cast the integer value to a duration value.
The int32 and time.Duration are different types. You need to convert the int32 to a time.Duration.
Example 2
package main
import (
"fmt"
"time"
)
func main() {
duration := time.Hour // duration of one hour
multiplier := 3 // multiply by 3
multipliedDuration := duration * time.Duration(multiplier)
fmt.Printf("Duration multiplied by %d: %v \n", multiplier, multipliedDuration)
}
Output
Duration multiplied by 3: 3h0m0s
In this example, we define a duration of one hour using the time.Hour constant. We also define a multiplier integer variable with a value of 3.
To multiply the duration by the integer, we use the multiplication operator * and the time.Duration type, casting the integer to a duration. This creates a new duration variable called multipliedDuration.
Finally, we print the multiplied duration using the fmt.Printf() function.
The output of this code snippet will be Duration multiplied by 3: 3h0m0s.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.