mismatched types time.Duration and int

10,617 views
Skip to first unread message

André Næss

unread,
Feb 9, 2012, 4:23:54 AM2/9/12
to golang-nuts
I was just fixing up some old code to match the latest weekly, and ran
into time.Duration for the first time. I have some code that is
printing the average processing time for some work items, and while
trying to convert the times into duration, I ran into this.

The following code works:

d, _ := time.ParseDuration("20.555s")
fmt.Printf("%s\n", d)
avg := d / 5
fmt.Printf("%s\n", avg)

It prints
20.555s
4.111s
as expected

Then I tried to update my original code, whose format was more like
this:

workItems := 5
d, _ := time.ParseDuration("20.555s")
fmt.Printf("%s\n", d)
avg := d / workItems
fmt.Printf("%s\n", avg)

And, it fails to compile saying "invalid operation: d / workItems
(mismatched types time.Duration and int)"

Now, I understand this message, and I can cast workItems into
time.Duration to fix it. What I don't understand is why the first
example works? Is there something magic about integer literals in Go
that I'm not aware of?

David Symonds

unread,
Feb 9, 2012, 5:38:00 AM2/9/12
to André Næss, golang-nuts
On Thu, Feb 9, 2012 at 8:23 PM, André Næss <andre...@gmail.com> wrote:

> Now, I understand this message, and I can cast workItems into
> time.Duration to fix it. What I don't understand is why the first
> example works? Is there something magic about integer literals in Go
> that I'm not aware of?

http://golang.org/doc/go_spec.html#Constants

In your first case, "5" is an untyped constant, so it is coerced to be
whatever type it needs to me. In your second case, the "5" on the
first line is, again, an untyped constant, but you are declaring a
variable at the same time, and that variable needs a type. The default
type of an ideal numeric constant without a decimal point is an int,
so workItems is declared as an int variable.


Dave.

Patrick Mylund Nielsen

unread,
Feb 9, 2012, 5:38:59 AM2/9/12
to André Næss, golang-nuts
When you enter the ideal in a statement with another type, it
automatically uses it as an uint64, int64, float64, or whatever the
type of the other number is.

When you do num := 1000, that's equivalent to doing var num int =
1000, and the two become incompatible.

Patrick Mylund Nielsen

unread,
Feb 9, 2012, 5:45:08 AM2/9/12
to André Næss, golang-nuts
In this case the int workItems is incompatible with the time.Duration
(int64) d, but doing "d / 2" would be equivalent to doing "d /
time.Duration(2)", i.e. "d / int64(2)"

So yes, it's a little magical, but in a good way :)

Reply all
Reply to author
Forward
0 new messages