t27.aiРусский

Functions

You will learn

The two ways t27 writes a function signature, and the body with return.

fn add(a: u8, b: u8) -> u8 declares a function with two u8 inputs and a u8 result; the body in braces ends with return. The compiler also accepts the Zig style, pub fn add(a: u8, b: u8) u8, without the arrow. There are no generics: fn id<T> is a parse error. The test runner on this site checks constants and does not call functions, so the lesson keeps the expected results as constants beside them.

Try it

Write a function sub in the player in either style and check the verdict stays clean.

Open the interactive lesson →

t27 basics 12: a function signature, piece by piece
t27 basics 12: a function signature, piece by piece ↗

The pieces of a t27 function signature in both styles the compiler accepts, and the generics it does not. Lesson 12 of the t27 basics course.

specs/basics/12_functions.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 12: Functions.
; A function takes typed inputs and returns a typed result.

module basics_12_functions;

pub fn add(a: u8, b: u8) -> u8 {
    return a + b;
}

pub fn twice(a: u8) u8 {
    return a + a;
}

pub const TWO_PLUS_THREE : u8 = 5;

test results_are_kept_as_constants {
    assert TWO_PLUS_THREE == 2 + 3;
}

Open the lesson's spec in the player ↗

All lessons