Radar · Go · Archive · Week 5 · Jan 27 – Feb 2, 2025
go/types: add Info.ImplicitConversions mapping
Worth knowingstdlib
- What changed
- The
TypeAndValuetype now hasAssignedTo()andUntyped()methods.AssignedTo()returns the type of the variable on the left side of an assignment, andUntyped()returns the untyped constant type of an expression. - Production impact
- The source does not say.
- Try it
- Call
AssignedTo()on aTypeAndValuefrom atypes.Infoto see the target type of an assignment. - Source
- github.com/golang/go/issues/70638
Understand it, then run it
Run it now
// This program demonstrates the current behavior of go/types in Go 1.27.1.
// It shows that the Type field of a TypeAndValue reports the default
// (typed) type of an expression, even when the expression is an untyped
// constant. The new AssignedTo and Untyped methods are not yet available,
// so we rely on the existing Type field to illustrate the issue.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
)
func main() {
// A simple source with an untyped constant used in an assignment.
src := `package main
var x any = 1 + 2
`
fset := token.NewFileSet()
// Parse the source.
file, err := parser.ParseFile(fset, "example.go", src, 0)
if err != nil {
panic(err)
}
// Prepare type-checking info.
info := &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
}
// Type-check the file.
conf := types.Config{Importer: nil}
if _, err := conf.Check("example", fset, []*ast.File{file}, info); err != nil {
panic(err)
}
// Find the expression 1+2 in the AST.
var expr ast.Expr
ast.Inspect(file, func(n ast.Node) bool {
if e, ok := n.(*ast.BinaryExpr); ok && e.Op == token.ADD {
expr = e
return false
}
return true
})
if expr == nil {
panic("expression not found")
}
tv := info.Types[expr]
// tv.Type reports the default type of the expression, which is 'int'.
fmt.Printf("Type of 1+2 (default type): %s\n", tv.Type)
// The untyped constant type is not directly exposed in 1.27.1.
// In future releases, tv.Untyped() would return UntypedInt.
}
What it printed when we ran it on Go 1.27.1
Type of 1+2 (default type): int
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed