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, durations are represented using the time.Duration type.
Step-by-step guide
- Create a duration of 2 hours using time.Duration.
- Multiply it by 3.
- Print the resulting duration.
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 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 is 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 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 seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Your blog brightens my day like a stream of warmth and positivity. Thank you for sharing your uplifting words.