The multiplication of golang numbers and time and the problem of redis
guys, I"m using some data from golang redis set. Using gopkg.in/redis.v4
usage: c.Set (uid + ": policy", b, exp * time.Second)
there is a problem here. Before this exp, I converted the string to int--> exp, _: = strconv.Atoi (policy.Exp)
and then I used exp * time.Second to report an error: invalid operation: time.Second times exp (mismatched types time.Duration and int)
.
I hard code handwritten a number multiplied by 700times time.Second is ok. But exp is not. I saw that the data types of 700and exp are all about int asking for advice. By the way, the value of exp is 700. thank you
this is actually an implicit constant and non-constant type conversion problem. Let's take a look at the time definition
.
type Duration int64
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
look at this again
Duration
700*time.Duration
Duration
exp := 700
exp*time.Duration
in order to be able to multiply, you must first convert the type to be consistent, so it is a question of whether it can be converted to type Duration:
700 (constant)-> Duration,700 is within the range of Duration, so you can convert
exp (int type)-> different types in Duration,go must be cast, so an error is reported
.
by the way, the document recommends time.Duration (700) * time.Second to use
in this way.
// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
// second := time.Second
// fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
// seconds := 10
// fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
//
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
take a look at the section under the key To convert an integer number of units to a Duration
.
In
time.Second * 1
, 1 is neither int, nor int64, but an untyped constant, which is equivalent to const exp = 1
and time.Second * a
.