Type aliasing refers to the technique of providing an alternate name for an existing type. Type aliasing was introduced in Go version 1.9 and above. This helps to facilitate code refactor for large codebases.

You can learn more about Type aliasing and the reasoning behind it in the Go proposal page:

https://go.googlesource.com/proposal/ /master/design/16339-alias-decls.md

Type Alias Syntax

Creating a type alias for an existing type is straightforward. An example syntax is as shown:

type new_name = existing_name

The syntax above does not create a new name for the existing_type. In essence, the new_name is just another spelling for the existing_type.

Using aliases allows you to introduce a new name for an existing type without breaking the code that references the old name.

To ensure compatibility between the existing type and the alias, the alias should have interchangeable parameter types. The example below shows code with interchangeable types:

package main

import (


    “fmt”


    “reflect”

)

type foo struct{}

// set new name as bar

type bar = foo


funcmyFunc (i bar) {


    fmt.Println(reflect.TypeOf(i))

}


funcmain() {


    vari bar


    myFunc(i)

}

Both types should convert from an empty interface.

package main

import (


    “fmt”


    “reflect”

)

type foo struct{}

// set new name as bar

type bar = foo


funcmyFunc (iinterface{}) {


    i, ok := i.(bar)


    if !ok {


        fmt.Println(“!bar type”)


    }


    fmt.Println(reflect.TypeOf(i))

}


funcmain() {


    vari bar


    myFunc(i)

}

Closing

Type aliasing refers to the method of adding a new name to an existing type to improve readability and code refactor. Check the Go docs to learn more.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png6215f5f79f2f6.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list