Type
is the base interface for all data types in Go. This means that all other data types (such as int
, float
, or string
) implement the Type interface. Type
is defined in the reflect
header.
The following is the Type
interface:
type Type interface {
// Underlying returns the underlying type of a type.
Underlying() Type
// String returns a string representation of a type.
String() string
}
Since it is implemented by all data types in Go, Type
can be used to extract information relating to the type for any and all data types.
A function that returns Type
returns the data type of the object it receives.
package mainimport "fmt"import "reflect"func learnType(t reflect.Type) string {if t != nil {return "Has a type!"}return "<nil>"}func main(){age := 10name := "Ben"height := 123.5fmt.Printf("The type of name is: %T\n", name)fmt.Printf("The type of age is: %T\n", age)fmt.Printf("The type of height is: %T\n", height)fmt.Print(learnType(reflect.TypeOf(age)))}
In the above example, we declare two variables. These variables are a string
, float
, and an int
. Using the %T
format specifier, we extract the type of each variable.
Next, we define a function learnType()
that takes the type of a variable and prints whether or not the object has a valid type.
Note:
Uninitialized variables have a default value ofnil
in Go.
Free Resources