int time.Duration the chicken and the egg

705 views
Skip to first unread message

joaqu...@gmail.com

unread,
Jan 28, 2014, 3:06:32 PM1/28/14
to golan...@googlegroups.com
Which came first, the time assertion? or the restriction of operation to tipes?



I can't do SOMEVAR* time.Seconds  but i can do 12 /* or any literal number */ * time.Seconds /* Or any duration */

Does somebody knows why?...  I just want to know the reason, please, i beg you.

Cheers

JD

Jeremy Jackins

unread,
Jan 28, 2014, 5:15:12 PM1/28/14
to golan...@googlegroups.com
c := 10

is short for

var c int
c = 10

You can't multiply an int and a time.Duration, because they are different types. You can multiply a time.Duration and an untyped integer constant (like 12), because time.Duration is an integer type.

Benjamin Measures

unread,
Jan 28, 2014, 5:35:32 PM1/28/14
to golan...@googlegroups.com
a := 15 * time.Second // this is ok

The above works because 15 is an integer literal <http://golang.org/ref/spec#Integer_literals>. This represents an integer constant <http://golang.org/ref/spec#Constants> "which may be given a type [...] implicitly when used [...] as an operand in an expression."

Thus, there is no type mismatch.

b := 15
c := b * time.Second

Here, variable b is declared to be equal to the [integer constant] 15. Variable b however, isn't an integer constant, since it is a [declared] variable. The type of b is given to be int, since it can represent the assigned integer constant.

Now, multiplying b with time.Second gives a "mismatched types" error since Go is a typed language and will not implicitly convert the type of variables.

In order to perform the operation, you'll need to convert the type of b:
c := time.Duration(b) * time.Second
"To convert an integer number of units to a Duration, multiply: [...]" <http://golang.org/pkg/time/#Duration>
Reply all
Reply to author
Forward
0 new messages