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

types2: math.MaxFloat32 is unexpectedly inferred as float64 #51556

Closed
changkun opened this issue Mar 9, 2022 · 4 comments
Closed

types2: math.MaxFloat32 is unexpectedly inferred as float64 #51556

changkun opened this issue Mar 9, 2022 · 4 comments

Comments

@changkun
Copy link
Member

changkun commented Mar 9, 2022

What did you do?

https://go.dev/play/p/uYfc9rcmP1j?v=gotip

package main

import "math"

type V[T ~float32 | ~float64] struct {
	X T
}

func NewV[T ~float32 | ~float64](x T) V[T] {
	return V[T]{x}
}

func main() {
	x := NewV(math.MaxFloat32)
	switch (interface{})(x).(type) {
	case V[float32]:
		println("OK")
	case V[float64]:
		panic("???")
	}
}

What did you expect to see?

OK

What did you see instead?

???

@krhubert
Copy link

krhubert commented Mar 9, 2022

MaxFloat32 is a float64 const. So everything works as expected here

@changkun
Copy link
Member Author

changkun commented Mar 9, 2022

MaxFloat32 is a float64 const

Aren't they untyped consts?

const (
	MaxFloat32             = 0x1p127 * (1 + (1 - 0x1p-23)) // 3.40282346638528859811704183484516925440e+38
	SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23            // 1.401298464324817070923729583289916131280e-45

	MaxFloat64             = 0x1p1023 * (1 + (1 - 0x1p-52)) // 1.79769313486231570814527423731704356798070e+308
	SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52            // 4.9406564584124654417656879286822137236505980e-324
)

@ALTree
Copy link
Member

ALTree commented Mar 9, 2022

fmt.Printf("%T\n", math.MaxFloat32) also prints float64, it's not related to type-inference. Spec:

An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required. [...] The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.

@changkun
Copy link
Member Author

changkun commented Mar 9, 2022

That's indeed a bit non-intuitive. If spec has defined default type, I don't see much more we can do here...

@changkun changkun closed this as completed Mar 9, 2022
@golang golang locked and limited conversation to collaborators Mar 9, 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