main
Raw Download raw file
 1const std = @import("std");
 2
 3var gpa_instance = std.heap.GeneralPurposeAllocator(.{}){};
 4const gpa = &gpa_instance.allocator;
 5
 6const Value = struct {
 7    data: f32,
 8    prev: []Value,
 9    pub fn init(data: f32, children: []Value) Value {
10        return Value{
11            .data = data,
12            .prev = children,
13        };
14    }
15};
16
17fn add(self: Value, other: Value) Value {
18    return Value{
19        .data = self.data + other.data,
20        .prev = []Value{ self, other },
21    };
22}
23
24fn mul(self: Value, other: Value) Value {
25    return Value{
26        .data = self.data * other.data,
27        .prev = &[0]Value{},
28    };
29}
30
31pub fn main() !void {
32    // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
33    std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
34    const a = Value.init(2.0, &[0]Value{});
35    const b = Value.init(-3.0, &[0]Value{});
36    const c = Value.init(10.0, &[0]Value{});
37    std.debug.print("Value A {}\n", .{a});
38    std.debug.print("Value B {}\n", .{b});
39    std.debug.print("Value C {}\n", .{c});
40    std.debug.print("A*B {}\n", .{mul(a, b)});
41    std.debug.print("A*B + C {}\n", .{add(mul(a, b), c)});
42
43    // stdout is for the actual output of your application, for example if you
44    // are implementing gzip, then only the compressed bytes should be sent to
45    // stdout, not any debugging messages.
46    const stdout_file = std.io.getStdOut().writer();
47    var bw = std.io.bufferedWriter(stdout_file);
48    const stdout = bw.writer();
49
50    try stdout.print("Run `zig build test` to run the tests.\n", .{});
51
52    try bw.flush(); // don't forget to flush!
53}
54
55test "simple test" {
56    var list = std.ArrayList(i32).init(std.testing.allocator);
57    defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
58    try list.append(42);
59    try std.testing.expectEqual(@as(i32, 42), list.pop());
60}