Search code examples
zig

I don't pub form zig and expected ',' after initializer


To make MyStruct publicly accessible, you should use the pub keyword when defining the struct. Here's how you can do it:

Fixed Code with pub for MyStruct:

pub fn main() void {
    const add = fn(a: i32, b: i32) i32 {
        return a + b;  // Semicolon added here
    };

    pub const MyStruct = struct {  // Struct is now public
        field1: i32,
        field2: i32,
    };

    // Example usage of MyStruct
    const instance = MyStruct{
        .field1 = 10,
        .field2 = 20,
    };

    const result = add(instance.field1, instance.field2);
}

Explanation:

  • pub const MyStruct: The pub keyword makes MyStruct accessible from other modules/files.
  • Struct Usage: After defining the struct, you can create an instance of it and access its fields.

Now, MyStruct is public and can be used elsewhere in your project.

https://chatgpt.com/c/be9b787c-671d-4272-b7bc-c70780e0281d

how to use code? I don't know.


Solution

  • This will add two integers, and I just started looking at getting started 10 minutes ago:

    const std = @import("std");
    
    pub const MyStruct = struct {  // Struct is now public
            field1: i32,
            field2: i32,
    };
    
    // Example usage of MyStruct
    const instance = MyStruct{
            .field1 = 10,
            .field2 = 20,
    };
    
    fn add(a: i32, b: i32) i32 {
            return a + b;  // Semicolon added here
    }
    
    pub fn main() void {
        var result: i32 = 0;
        result = add(instance.field1, instance.field2);
        std.debug.print("{}\n", .{result});
    }