
Clive B.
—I don’t know how to identify the type of a variable in Go.
You can use either the %T verb from the fmt package or the Go type switches to determine variable types in Go.
For the purposes of print debugging, you can get the string representation of a variable using the fmt package with the %T verb:
package main import "fmt" func main() { example := "some string" fmt.Printf("variable's type is: %T", example) }
This prints:
variable's type is: string
However, if you need to identify the type of a variable for a specific purpose, it is best to use a type switch. Type switches are similar to normal switch statements, only they switch types rather than values:
package main import "fmt" func main() { printType("example") // Prints "received a string". printType(42) // Prints "received an int". printType(4.2) // Prints "received an unknown type". } func printType(value any) { switch value.(type) { case int: fmt.Println("received an int") case string: fmt.Println("received a string") default: fmt.Println("received an unknown type") } }
The reflect package can also be used to inspect the type information of a variable more deeply:
package main import ( "fmt" "reflect" ) func main() { example := 42 reflectType := reflect.TypeOf(example) fmt.Printf("example type bits: %d, size (in bytes): %d, string representation: %s", reflectType.Bits(), reflectType.Size(), reflectType.String()) }
This prints:
example type bits: 64, size (in bytes): 8, string representation: int
While the reflect package is interesting and contains detailed information about the types in your program, it is not performant and you should avoid using it in production environments when possible.
reflect packageTasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
