Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

What is the Type type in Golang?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
}
All data types implement the Type interface

Use

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.

Code

package main
import "fmt"
import "reflect"
func learnType(t reflect.Type) string {
if t != nil {
return "Has a type!"
}
return "<nil>"
}
func main(){
age := 10
name := "Ben"
height := 123.5
fmt.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 of nil in Go.

RELATED TAGS

golang

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring