Skip to content

How to Multiply a Duration by an Integer?

time package is your friend if you want to have different durations in golang! Duration has int64 type then you can multiply it with int64 numbers.

type Duration int64

Imagine we want 10 nanoseconds, 10 milliseconds, 10 seconds, 10 minutes, and 10 hours:

10 * time.Nanosecond
10 * time.Millisecond
10 * time.Second
10 * time.Minute
10 * time.Hour

This snippet sleep for 3 seconds between two prints:

package main

import (

func main() {
	fmt.Println("Hi! wait ...")
	time.Sleep(3 * time.Second)
	fmt.Println("After three seconds :)")

If you faced this error:

invalid operation: duration * time.Second (mismatched types int and time.Duration)

Then your number is not int64, use this trick:

duration := int(2) // this is int not int64
time.Sleep(time.Duration(duration) * time.Second)

Leave a Reply

Your email address will not be published. Required fields are marked *