So ChatGPT seems convinced that in Zig there is something called shorthand syntax for single-expression functions and it works like this:
fn add(x: i32, y: i32) i32 => x + y;
But when I try to use that I get:
error: expected ';' or block after function prototype
fn add(x: i32, y: i32) i32 => x + y;
^~
I cannot find any documentation about single-expression functions, so is ChatGPT hallucinating here?
Does zig have special syntax for single-expression functions?
The ChatGPT transcript (for completeness):
me: does zig have implicit return?
While Zig does not have implicit return, it does have a shorthand syntax for functions that contain only a single expression. In this case, you can omit the curly braces and use the
=>
operator to specify the return value. For example, theadd
function could be rewritten using this shorthand syntax like this:fn add(x: i32, y: i32) i32 => x + y;
In this example, the function body consists of a single expression x + y, and the
=>
operator is used to specify the return value of the function.
me: since which version of zig is that supported?
The shorthand syntax for single-expression functions using the
=>
operator was introduced in Zig version 0.7.0, which was released on October 6, 2020. This version introduced a number of new language features and improvements, including the=>
operator for single-expression functions.Before Zig 0.7.0, all functions in Zig had to be defined using curly braces and an explicit return statement. However, the
=>
operator provides a more concise syntax for simple functions with a single expression, making the code easier to read and write.It's worth noting that the
=>
operator is not a replacement for the traditional syntax, but rather a shorthand for simple functions. In Zig, you can still use the traditional syntax with curly braces and an explicit return statement for more complex functions that require multiple statements or control flow.