How to Define Custom Types with type in Go

Define custom types in Go using the type keyword to create aliases or distinct named types for better code clarity and safety.

Use the type keyword to define a new type alias or a new named type based on an existing one. Aliases are interchangeable with the original type, while named types create a distinct type that requires explicit conversion.

// Type alias: interchangeable with string
type MyString = string

// Named type: distinct from string, requires conversion
type MyStringType string

var s string = "hello"
var a MyString = s          // OK: alias
var b MyStringType = s      // Error: cannot use string as MyStringType
var c MyStringType = "hi"   // OK: literal
var d string = string(b)    // OK: explicit conversion