#File naming conventions and structs clarification

1 messages · Page 1 of 1 (latest)

tulip steeple
#

The zig docs say:

File names fall into two categories: types and namespaces. If the file (implicitly a struct) has top level fields, it should be named like any other struct with fields using TitleCase. Otherwise, it should use snake_case. Directory names should be snake_case.

This suggests that "file namespaces" only contain functions, no global variables, while those with fields are considered "file struct"

First, does "top level fields" mean public mutable fields (pub var) only? or does it include const/comptime variables? and what about non-public vars that only get updated as a side-effect of a function?

Second, I am a bit confused on how structs work
From the zig docs: test_namespaced_container_level_variable.zig

const std = @import("std");
const expect = std.testing.expect;

test "namespaced container level variable" {
    try expect(foo() == 1235);
    try expect(foo() == 1236);
}

const S = struct {
    var x: i32 = 1234;
};

fn foo() i32 {
    S.x += 1;
    return S.x;
}

S seems to me like a Type type with a struct that holds 1 i32 per "instance" of it, that is by-default when x is not specified, defaults to the value 1234

Why is it then possible to mutate and access this struct field?

#

Oh wait I think I just realized, it has var which makes it some sort of struct scoped "global" variable, so without a var/const it's a field but with that its not?

lilac siren
#

in your example code S should be lowercase (s), as it's only used to namespace the global variable x.
"global variable" meaning "a value that lives in static memory"

tulip steeple
#

Thanks, that makes sense, any idea about the first question?

lilac siren
# tulip steeple Thanks, that makes sense, any idea about the first question?

Zig files are all implicitly structs, you can define fields on them:

// Foo.zig

field: usize,
another_field: []const u8,

pub fn init() @This() {
    return .{
        .field = 0,
        .another_field = "abc",
    };
}
```for examples in the standard library, there's [`Allocator.zig`](https://ziglang.org/documentation/master/std/#src/std/mem/Allocator.zig)
tulip steeple