How to multiply duration by integer in GO? [SOLVED]


GOLANG Solutions, GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In this tutorial, we will walk through some examples of converting int to time.Duration and doing some operations (division, multiply) with it. The built-in package time in Golang provides functionality for measuring and displaying time. The calendrical calculations always assume a Gregorian calendar, with no leap seconds.

type Duration int64: A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

The millisecond, second, minute,.. are time.Duration type:

type Duration int64

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

These are all time.Duration type, but underneath it's an int64 that may be used by a numeric untyped integer and is assignable.

 

Can we multiply time.Duration by an integer (int32)?

The example below prints out a message and sleep for a few second then print the next message:

package main

import (
	"fmt"
	"time"
)

func main() {
	var timeout = 3
	fmt.Println("This is the first message!")

	// sleep for 3 second
	time.Sleep(timeout * time.Second)

	fmt.Println("This is the second message!")
}

Output:

# command-line-arguments
.\duration.go:13:13: invalid operation: timeout * time.Millisecond (mismatched types int and time.Duration)

The program has crashed because numeric operations require the same input type unless they include shifts or untyped constants. In this example, we can not multiply a time.Duration by an integer.

 

Example 1: Multiply time.Duration by a constant

In this example, we will declare a constant and try to multiply a duration by this constant:

package main

import (
	"fmt"
	"time"
)

const timeout = 3

func main() {

	fmt.Println("This is the first message!")

	// sleep for 3 second
	time.Sleep(timeout * time.Second)

	fmt.Println("This is the second message!")
}

The compiler knows the underlying type of duration is int64. Literals and constants are untyped unless the type is expressly defined until they are used. In this case, timeout is a constant without a type. The implicit conversion of its type to time.Duration. This application will print the results:

 

Example 2: Multiply a time.Duration by an untyped literal constant

In this example, we will use an untyped literal constant with a default type of integer, it has an ideal type.

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("This is the first message!")
	time.Sleep(3 * time.Second)
	fmt.Println("This is the second message!")
}

The output will be the same as the example 2. Noted that: 3 * time.Second can be directly calculated because Go converts the untyped constants to numeric types automatically. Here, it converts 3 to time.Duration automatically, because it's an alias to Int64.

 

Example 3: Convert an int variable to time.Duration

In the example below, we will declare an int variable and then convert it to a time.Duration. Finally, we multiply it by the time.Duration:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("This is the first message!")

	// sleep for 3 second
	timeout := 3
	// convert int to time.Duration
	time.Sleep(time.Duration(timeout) * time.Second)

	fmt.Println("This is the second message!")
}

We have the same output as example 1.

 

Summary

In Golang, unlike other languages, time.Duration has its own type. Integer and time.Duration are two different types, so the multiplication of them results in an error and crashing of the code. The solution is using a constant or converting int to <span class="mini-code">time.Duration</span> by using <span class="mini-code">time.Duration()</span> function and then multiplying them.

 

References

https://pkg.go.dev/time
How to multiply duration by integer? - Stack Overflow

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment