Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: time: enable warnings when doing time.Duration multiplication #64420

Closed
vax-r opened this issue Nov 28, 2023 · 2 comments
Closed

proposal: time: enable warnings when doing time.Duration multiplication #64420

vax-r opened this issue Nov 28, 2023 · 2 comments
Labels
Milestone

Comments

@vax-r
Copy link

vax-r commented Nov 28, 2023

Proposal Details

As we are using time.Sleep() function, we often just throw in an integer like the following

time.Sleep(5 * time.Second)

What if we throw a type Duration with some time units like 's' instead of an integer?
I've done this before when trying to set some time arguments in environment variable and read it into a Go program, like the following

set_time, err := time.ParseDuration(os.Getenv("WAIT_TIME"))
if err != nil {
    panic(err)
}
time.Sleep(set_time * time.Second)

Basically WAIT_TIME is about 5s, and the program will wait for a super long time.
I guess the reason is that we've done something like time.Duration * time.Second in set_time * time.Second, since set_time is basically 5s with type time.Duration, which is meaningless in this kind of situation (we're not dealing with acceleration)

time.Duration is in fact int64, so I think the compiler may just think this behavior as int64 * int64, but it doesn't make sense here

I suggest we should add some detecting mechanism to prevent this kind of undefined behavior from happening, what do you think?
If you guys think it makes sense I can start to work on it.

@vax-r vax-r added the Proposal label Nov 28, 2023
@gopherbot gopherbot added this to the Proposal milestone Nov 28, 2023
@vax-r vax-r changed the title proposal: src/time/time.go: enable warnings when doing time.Duration multiplication proposal: time: enable warnings when doing time.Duration multiplication Nov 28, 2023
@seankhliao
Copy link
Member

I don't this will meet the precision criteria for checks by cmd/vet.
The operation is valid and used in many places.

You are, of course, free to write your own linter. If it becomes popular, we can consider adopting a similar check for vet

@AlexanderYastrebov
Copy link
Contributor

https://pkg.go.dev/time

To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Nov 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants