Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 147 ยท Variables and Types

Type Conversion and Inference

Learn Go type conversion - no implicit conversions, numeric truncation, strconv for strings and numbers, type inference with := and defined types vs aliases.

In many languages you can add an integer to a float, pass a small number where a big one is expected, or compare a number with a string, and the language quietly converts things behind your back. Go takes the opposite approach: there are no implicit conversions between typed values. If you want to turn an int into a float64, you say so, in the code, where the next reader can see it.

This feels strict for about a day, then it feels like a relief: you never wonder whether a hidden conversion lost precision or changed a sign. This lesson explains the conversion syntax T(x), what happens to the value for each kind of conversion (widening, narrowing, float to int, number to string and back), how type inference decides types for you, why untyped constants are so flexible, and how defined types differ from aliases. It continues from basic types and numbers.

Explicit conversion: T(x)

To convert a value x to type T, write T(x). It looks like a function call, but it's a conversion built into the language:

Go Converting between numeric types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If you forget a conversion, the compiler tells you immediately:

Go No implicit conversion (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is:

TEXT
./main.go:8:17: invalid operation: a + b (mismatched types int32 and int64)

Fix it by converting one side: int64(a) + b. Even int and int64 count as different types, although both are 64 bits on our server.

What conversions do to the value

A conversion keeps the value if the target type can hold it. If it can't, Go doesn't raise an error; it follows precise rules.

Widening is safe

Converting to a bigger type of the same kind (int8 to int64, float32 to float64) never loses information. A signed value is sign-extended and an unsigned one is zero-extended.

Narrowing truncates

Converting to a smaller integer type keeps only the low-order bits that fit. The result can look nothing like the original:

Go Narrowing and sign changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

None of these conversions crash. When a value might not fit, check it first:

Go A checked narrowing conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Float to integer truncates toward zero

Converting a float to an integer drops the fractional part. It does not round:

Go Floats to integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Note that f and g are variables. With a constant, int(3.99) is a compile error, because the compiler rejects constant conversions that lose information.

If a float is too large for the target integer, or is NaN or infinity, the result is implementation-dependent: Go does not define it, and it can differ between machines. Check the range with math.IsNaN, math.IsInf and comparisons before you convert.

Converting an integer to a float is exact for small values, but a float64 has only 53 bits of precision, so integers above 2^53 may be rounded.

Numbers and strings

Converting between numbers and their text form needs a library function, because it's a real transformation, not a reinterpretation of the same bytes. The tools are in the strconv package (and fmt.Sprint for formatting):

Go Number to string and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

strconv.Atoi and ParseFloat return an error for text that isn't a valid number, so you always get a chance to react. The ParseBool function accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false and False, but not "yes".

The conversion string(x) has a different meaning, covered in strings and runes: from an integer type it produces the character with that code point, not the digits. Strings also convert to and from []byte and []rune, and the conversion copies the data.

Conversions between slice and array types

Some conversions work between composite types. A slice can convert to an array (Go 1.20) or to an array pointer (Go 1.17), and Go panics if the slice is too short:

Go Slice to array conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The array copy is independent of the slice; the array pointer shares memory with it.

Type inference

When you write x := value or var x = value, Go infers the type of x from the value on the right. You've used it since the first lesson, but it is worth knowing the exact rules:

  • A typed value gives its own type: a := someFunc() has the result type of someFunc.
  • An untyped constant gives its default type: int, float64, rune, string, bool or complex128.
  • For an expression with untyped constants of different kinds, the kind that comes later in the list integer, rune, floating-point, complex wins.
Go What type did Go infer?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Inference makes code shorter, but it can hide a type you'd rather choose. ratio := 1 is an int; if you wanted a float, write ratio := 1.0 or var ratio float64 = 1. Inference also works for generic function calls, covered in generics.

Why untyped constants are flexible

Constants without a type convert silently when it is safe, which is why this compiles even though Go has no implicit conversions between variables:

Go Untyped constants versus typed variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The case 5 * time.Second is a pattern you'll see all the time. The reason seconds * time.Second fails is that seconds is an int variable and time.Second has type time.Duration, a different type. This detail trips up almost everyone once.

Defined types and aliases

You can create your own type from an existing one:

Go
type Celsius float64          // a defined type
type Temp = float64           // an alias

A defined type (Celsius) is a brand-new type that has the same representation (its underlying type) as float64 but is not interchangeable with it. An alias (Temp) is only another name for the same type. The next lesson covers both in depth; for conversions, the rule is simple. Values of different defined types never mix, but you can convert between them when their underlying types match:

Go Converting between defined types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Converting between interface values and concrete types is a different mechanism, called a type assertion, which you'll meet in type assertions and switches.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line compiles, given var i int = 5 and var f float64 = 2.5?

    Go has no implicit numeric conversions. You write T(x), so float64(i) * f is the correct form.
  2. 2. What does this print? g := -3.99; fmt.Println(int(g))

    Converting a float to an integer truncates toward zero, so -3.99 becomes -3.
  3. 3. What does fmt.Println(uint8(300)) do when 300 is written directly as a constant?

    Constant conversions that lose information are compile errors. Only conversions of variables wrap around silently.
  4. 4. Why does time.Sleep(n * time.Second) fail to compile when n is an int variable?

    Untyped constants adapt, but the variable n has the fixed type int. Write time.Duration(n) * time.Second.
  5. 5. What is strconv.Itoa(65), and how does it differ from string(rune(65))?

    Itoa produces the decimal digits of the number. Converting a rune to a string gives the character with that code point.

Summary

  • Go never converts between different typed values implicitly. Write T(x) yourself, for example float64(count) * price.
  • Widening is lossless. Narrowing integer conversions keep the low bits (wraparound), and float to int truncates toward zero. Constant conversions that lose information are compile errors.
  • Convert numbers to and from text with strconv (Itoa, Atoi, ParseFloat, FormatFloat, ParseBool) or fmt.Sprint; string(int) produces a character, not digits.
  • := and var x = v infer the type from the value; untyped constants fall back to int, float64, rune, string, bool or complex128.
  • Untyped constants adapt to context (2 * f, 5 * time.Second), but variables have a fixed type and need an explicit conversion.
  • Defined types are distinct types convertible when their underlying types match; aliases are the same type under another name.

Next: Defined Types and Type Aliases