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

Feature request: 2.5*time.Hour #32666

Open
cfhay opened this issue Jun 18, 2019 · 4 comments

Comments

@cfhay
Copy link

commented Jun 18, 2019

What version of Go are you using (go version)?

play.golang.org reports 1.12.5

What did you do?

https://play.golang.org/p/klT3SFB7BJE

What did you expect to see?

2h30m0s

What did you see instead?

./prog.go:9:23: constant 2.5 truncated to integer

In the code I'm multiplying a constant with a constant and according to https://blog.golang.org/constants this should just work. But somehow it doesn't.

@ericlagergren

This comment has been minimized.

Copy link
Contributor

commented Jun 18, 2019

Per the spec, it’s illegal for a constant expression to truncate a floating point number: https://golang.org/ref/spec#Constant_expressions

The values of typed constants must always be accurately representable by values of the constant type. The following constant expressions are illegal:

[...]
int(3.14)    // 3.14 cannot be represented as an int

What part of the blog post led you to think it would work? That might clear up some confusion.

@cfhay

This comment has been minimized.

Copy link
Author

commented Jun 18, 2019

@beoran

This comment has been minimized.

Copy link

commented Jun 19, 2019

FWIW: It does work if you do it like this:

package main

import (
	"fmt"
	"time"
)

const Duration = int64(float64(time.Hour) * 2.5)

func main() {
	fmt.Printf("%v", Duration)
}

https://play.golang.org/p/E9tMZox7lv0

@deanveloper

This comment has been minimized.

Copy link

commented Jul 4, 2019

I can get behind this proposal.

time.Second is a typed constant with the (evaluated) value time.Duration(1000000000)

In constant arithmetic, 2.5 * 1000000000 correctly evaluated to 2500000000, an untyped integer that does not need to be truncated.

I believe this proposal is saying that untyped float constants multiplied by typed integer constants should be evaluated as typed integer constants, provided that no truncation occurs (such as the case of 2.5 * time.Second or 2.5 * time.Hour)

EDIT - It looks as if the proposal is stating that the current behavior (not compiling) is a bug. It is definitely not. However it could be useful to add this in as a feature for constants.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
5 participants
You can’t perform that action at this time.