liveBook · Manning

Type inference

As explained in Systems Programming with Zig

Type inference is compiler deduction of a program expression's data type from its context and values.

In Zig, a function’s declared return type can provide context for inferring returned values: the Fibonacci base cases 0 and 1 are inferred as i32. section 2.1.3

Listing 2.2 Recursive fibonacci
const std = @import("std");

fn fibonacci(n: usize) i32 { // #1
    // #2
    if (n == 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n - 2); // #3
}

pub fn main() void {
    // #4
    const first = fibonacci(1);
    const second = fibonacci(2);
    const third = fibonacci(3);
    const fourth = fibonacci(4);
    std.debug.print("{} {} {} {}\n", .{ first, second, third, fourth });
}

The Fibonacci function shows the declared i32 return type alongside its base-case returns. section 2.1.3

How Systems Programming with Zig covers it

How deep it goes
Explains inference of base-case literals from a function return type, without detailing broader inference rules.
Examples
Uses Fibonacci base cases returning 0 and 1, inferred as i32.
What you can do after
Understand how Zig infers returned literal types from a function’s declared return type.
How it connects
Relates type inference to function return types and return statements.

Also explained in

Compare how 19 books explain type inference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.