CodeBlanks Logo Icon CodeBlanks

Type definitions

Learn to define new types with the type keyword.

Type definitions

The type keyword creates a new, named type from an existing one. The new type holds the same data but the compiler treats it as a separate type:

type Celsius float64
type Fahrenheit float64

var c Celsius = 25
var f Fahrenheit = 77
// c + f  → compile error: different types

This catches mixed-up units at compile time.

Adding methods and aliases

You can add methods to your own type; this is the real power of type definitions:

func (c Celsius) Fahrenheit() Fahrenheit {
    return Fahrenheit(c*9/5 + 32)
}
fmt.Println(Celsius(100).Fahrenheit())  // 212

type Ad = string (with an equals sign) isn't a new type, just an alias; byte and rune are defined this way.

Practice Temperature type

Define type Celsius float64 and type Fahrenheit float64. Compute c*9/5 + 32 with the method func (c Celsius) Fahrenheit() Fahrenheit and print Celsius(25).Fahrenheit().

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Celsius float64
type Fahrenheit float64

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

func main() {
    fmt.Println(Celsius(25).Fahrenheit())
}

Expected output

77

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 After <code>type Yas int</code>, why doesn't <code>var y Yas = 5; var n int = y</code> compile?

  • Yas and int are different types; int(y) is needed Correct answer
  • 5 can't be a Yas
  • Yas isn't a number
  • It compiles

Explanation: There is no implicit assignment between named types; even with the same underlying type, an explicit conversion is written.

2 New type

Question
____ Metre float64
var uzunluk Metre = 3.5
Answer
type Metre float64
var uzunluk Metre = 3.5

Explanation: The type keyword defines a new, named type.

3 Definition and meaning

Term Meaning
type Celsius float64 A new type
type Ad = string An alias
Celsius(25) A conversion
func (c Celsius) A method

All lessons in Beginner