go go/book/learninggo

Types

The type keyword is used to define new types, giving aliases or custom names to existing types, creating structs, defining interfaces, or declaring function signatures.
It’s one of the key mechanisms that Go provides for customizing and structuring code.

Creating Aliases for Existing Types

type Age int        // Defines Age as an alias for int
type Name string    // Defines Name as an alias for string
 
func main() {
    var myAge Age = 30
    var myName Name = "Alice"
    fmt.Println(myAge, myName) // Output: 30 Alice
}

Declaring Custom Function Types

Go - Functions > Function Types

type Adder func(int, int) int
 
func add(a int, b int) int {
    return a + b
}
 
func main() {
    var myAdder Adder = add
    fmt.Println(myAdder(3, 4)) // Output: 7
}

Defining Custom Error Types

type MyError struct {
    Message string
}
 
func (e *MyError) Error() string {
    return e.Message
}