Reputation: 1421
I'm new to GoLang and at the moment at a loss why the compiler does not accept a particular line of code.
I've got this working example for creating a timeout when dialing:
conn, err := grpc.Dial(*connAddress,
grpc.WithInsecure(),
grpc.WithBlock(), // will block till the connection is available
grpc.WithTimeout(100*time.Second)) // times out after 100 seconds
Now the hardcoded 100 there is not nice, so I would like to make that a commandline variable via a flag, like so:
connTimeout := flag.Int64("connection-timeout", 100, "give the timeout for dialing connection x")
...
conn, err := grpc.Dial(*connAddress,
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithTimeout(*connTimeout*time.Second))
However this gives the following compilation error:
mismatched types int64 and time.Duration
So apparently I can't use the int64 flag variable directly to calculate a duration but a number can?
Eventually I found a solution for using the flag variable by creating a variable related to time.Duration first:
var timeoutduration = time.Duration(*distributorTimeout) * time.Second
// create distributor connection
conn, err := grpc.Dial(*connAddress,
grpc.WithBlock(),
grpc.WithTimeout(timeoutduration))
The above seems to work as expected: the dialing is tried for as long as the commandline parameter given (default 100) and than throws a message that the connection could not be made. Good.
However: How come directly using the int64 flag-variable is not possible for calculating a time.Duration, in other words what is the difference for golang between the number 100 and the variable that contains the int64?
Upvotes: 1
Views: 10509
Reputation: 255155
grpc.WithTimeout(100*time.Second)
and grpc.WithTimeout(*connTimeout*time.Second)
does not because of assignability rules:
the latter expression satisfies none of those, and the former satisfies the
x
is an untyped constant representable by a value of type T
.rule
Upvotes: 2