#Optional type?.*

1 messages · Page 1 of 1 (latest)

hardy canopy
#
const std = @import("std");
const print = std.debug.print;

const Node = struct {
    value: u8,
    left: ?*Node,
    right: ?*Node,
    height: u8,

    pub fn new(value: u8) Node {
        return Node{ .value = value, .left = null, .right = null, .height = 1};
    }

    pub fn display(node: ?*Node) void {
        if(node != null) {
            print("{u} ", .{node.?.value});
        } else {
            print("{any} ", .{node});
        }
    }
};

const AVL_Tree = struct {
    root: ?*Node,
    
    pub fn create() AVL_Tree{
        return AVL_Tree{ .root = null };
    }

    pub fn insert(this: *AVL_Tree, node: *Node) void {
        var curr_node: Node = this.root.?.*;
        _ = curr_node;        

        if(this.root == null) {
            this.root = node;
        }     
    }

    pub fn display(this: *AVL_Tree) void {
        if(this.root) |val| {
            val.display();
            if(this.root.?.*.left) |left| {
                left.display();
            }

            if(this.root.?.*.right) |right| {
                right.display();
            }
        }
    }
};


pub fn main() !void {
    var tree: AVL_Tree = AVL_Tree.create();
    tree.display();

    var n1 = Node.new(12);
    var n2 = Node.new(6);

    tree.insert(&n1);
    tree.insert(&n2);
    tree.display();
}
#
thread 4511 panic: attempt to use null value
/home/thomas/priv/zig/AVL-Tree/src/main.zig:31:34: 0x21eb21 in insert (main)
  var curr_node: Node = this.root.?.*;
                                 ^
crisp sapphire
#

You unwrap this.root.?.* and THEN you check if it's null.

hardy canopy
#

True

#

Litterly as I posted it I got it

#

I am doing it right already just 20 lines below

crisp sapphire
#

ya, but why call this.root.?.* again there when you have val ?