Home
Go
type Keyword (Type Alias)
Updated Apr 23, 2025
Dot Net Perls
Type. 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.
struct
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.
Part 1 We declare a Cat struct, and this struct has one field in it: an int field. This type declaration does not create an instance of the type.
Part 2 Here we see 2 type aliases for the Cat struct. This means the terms Kitty and Meow can be used in place of Cat.
Part 3 We use the Cat type and its 2 aliases (Kitty and Meow) to create 3 instances of the Cat type. Each cat has 4 paws.
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}
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 23, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen