go: Untyped consts should not be automatically type converted
What version of Go are you using (go version
)?
$ go version go version go1.15 linux/amd64
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 GO111MODULE="" GOARCH="amd64" GOBIN="" GOCACHE="/.cache/go-build" GOENV="/.config/go/env" GOEXE="" GOFLAGS="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOINSECURE="" GOMODCACHE="/go/pkg/mod" GONOPROXY="" GONOSUMDB="" GOOS="linux" GOPATH="/go" GOPRIVATE="" GOPROXY="https://proxy.golang.org,direct" GOROOT="/usr/local/go" GOSUMDB="sum.golang.org" GOTMPDIR="" GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64" GCCGO="gccgo" AR="ar" CC="gcc" CXX="g++" CGO_ENABLED="1" GOMOD="" CGO_CFLAGS="-g -O2" CGO_CPPFLAGS="" CGO_CXXFLAGS="-g -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build533260346=/tmp/go-build -gno-record-gcc-switches"
What did you do?
https://play.golang.org/p/iLPNLfxLl5e
What did you expect to see?
All five calls to foo
should have been compiler errors due to an implicit conversion from int
to time.Duration
.
What did you see instead?
If the variable in question is a const
, it is automatically type converted. In our case, this lead to a bug.
I understand that this is as per the Go spec:
A value x is assignable to a variable of type T (“x is assignable to T”) if one of the following conditions applies: […] x is an untyped constant representable by a value of type T.
However, since this can easily lead to a bug, it would be nice if go vet at least warned about this situation.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 3
- Comments: 16 (10 by maintainers)
time.Duration
is one particular case. Existing code uses many types that are intended to support conversion from untyped constants, as well as many types that are not intended to support conversion from untyped constants. At this point we can’t arbitrarily declare that all such conversions are invalid. That would break working, correct code. And we can’t make that change in “go vet” either.@rittneje Run staticcheck (https://staticcheck.io/). It has checks for many things, including apparent misuses of
time.Duration
.