In Go we use the type keyword to declare a type (like a struct
) or a type alias (an identifier that can be used instead of a type name).
To declare a struct
, we must use the type keyword before the struct
name. For type aliases, we can use a block to set up multiple aliases.
This program uses the type keyword in 2 ways: first it declares a struct
type (Cat) with it, and then it sets up 2 type aliases to the Cat type. In the main()
method we use the various types.
struct
, and this struct
has one field in it: an int
field. This type declaration does not create an instance of the type.struct
. This means the terms Kitty and Meow can be used in place of Cat.package main
import (
"fmt"
)
// Part 1: use type to specify a new struct type.
type Cat struct {
paws int
}
// Part 2: use type to set up type aliases.
type (
Kitty = Cat
Meow = Cat
)
func main() {
// Part 3: use the struct type and its various aliased types.
c := Cat{paws: 4}
fmt.Println(c)
k := Kitty{paws: 4}
fmt.Println(k)
m := Meow{paws: 4}
fmt.Println(m)
}{4}
{4}
{4}
In Go we cannot just use the struct
keyword to declare a struct
—we must prefix the struct
name with the type keyword. With type aliases, we can make certain programs compile correctly.