CodeNebula
Go🔧Core Languagebeginner

Named Types and Type Definitions

Go · Core Language · Run with go run

Explanation

`type Celsius float64` creates a new named type distinct from its underlying type — values are not interchangeable without an explicit conversion, which prevents whole classes of unit-mixing bugs. A *type alias* `type Byte = uint8` (with `=`) is different: it creates no new type, just another name. Named types can carry their own methods.

Real-World Scenario

A measurement library defines `type Celsius float64` and `type Fahrenheit float64`. Because they are distinct types, the compiler rejects accidentally passing a `Fahrenheit` where a `Celsius` is expected — the bug is caught at compile time, not in production.

Quick Snippet

snippet.go
type Celsius float64
type Fahrenheit float64

func (c Celsius) ToF() Fahrenheit {
    return Fahrenheit(c*9/5 + 32)
}

var c Celsius = 100
var f Fahrenheit = c.ToF() // 212

// var bad Fahrenheit = c   // compile error: cannot use c (Celsius) as Fahrenheit

type Byte = uint8 // alias — Byte and uint8 are the SAME type

Full Example

named_types.go
// Compile: go run named_types.go
// Output:
//   100C = 212F
//   0C = 32F
//   Byte alias holds: 255
package main

import "fmt"

// Distinct named types — not interchangeable without conversion
type Celsius float64
type Fahrenheit float64

func (c Celsius) ToF() Fahrenheit {
	return Fahrenheit(c*9/5 + 32)
}

// Type alias — Byte and uint8 are the SAME type
type Byte = uint8

func main() {
	var c Celsius = 100
	fmt.Printf("%gC = %gF\n", float64(c), float64(c.ToF()))

	c = 0
	fmt.Printf("%gC = %gF\n", float64(c), float64(c.ToF()))

	var b Byte = 255
	fmt.Println("Byte alias holds:", b)
}
Run command
go run named_types.go