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

cmd/go: Can not shift constant integer while convert result to floating-number #51585

Closed
mkideal opened this issue Mar 10, 2022 · 3 comments
Closed

Comments

@mkideal
Copy link

mkideal commented Mar 10, 2022

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

$ go version
go1.17.8

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env

What did you do?

Compile following code:

package main

import (
	"fmt"
)

func main() {
	var x = 2
	fmt.Println(float64(1 << x))
}

Playground: https://go.dev/play/p/GbHxUjOVJD6

What did you expect to see?

Output: 4

What did you see instead?

Compile error: invalid operation: 1 << x (shift of type float64)

If i change the code to float64(int(1) << x), it's ok. But this error doesn't look like an error.

@blackgreen100
Copy link

I believe this is consistent with the language specifications.

If the left operand of a non-constant shift expression is an untyped constant, it is first implicitly converted to the type it would assume if the shift expression were replaced by its left operand alone.

  • The shift expression 1 << x is non-constant because it involves the variable x
  • the left operand is the untyped constant 1
  • implicitly converted to the type it would assume if there were no shift -> float64(1)
  • shift on float64 is an invalid operation

@mkideal
Copy link
Author

mkideal commented Mar 10, 2022

It's a reasonable explanation, but it looks a little weird.

@robpike
Copy link
Contributor

robpike commented Mar 10, 2022

Working as described by the spec. Not exactly as intended, as the shift rules were incredibly difficult to sort out - I was joking about them to Robert Griesemer just yesterday - but how they work. The behavior of this expression is a casualty of making things seem right in more idiomatic contexts.

@robpike robpike closed this as completed Mar 10, 2022
@golang golang locked and limited conversation to collaborators Mar 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants