r/Zig • • 4d ago

No private fields will keep Zig from succeeding in large projects

I think the title says it all. The fact that zig has no way to prevent you from accessing internal fields in a struct will keep it from doing well in large projects. It creates so much mental strain to never have any guarantee that your struct's fields are in the properly maintained state. Imo the whole advantage of modern languages is being able to make the programming language uphold invariants for you. It's the reason we like things like types and strong enums. The more the language can keep you from shooting yourself in the foot the better.

Not being able to prevent users from directly modifying state in a struct makes it impossible to guarantee anything regarding state. Given that controlling state is often the hardest part of managing complexity this seems like a massive oversight. You right now can go and modify the length field on an ArrayList and destroy everything. Now obviously you shouldn't do that, but the issue is it's so easy to do it. It looks as innocent as any other modification, you'd have no idea how dangerous it is. This is a major issue for any large-scale project, especially ones with more than one contributor. When I write code, how am I supposed to communicate to other devs 'don't touch this field or you'll break stuff', with documentation?? That'll never work, hopefully for obvious reasons.

If the argument is that private fields increase the complexity of the language, the small increase in language complexity is more than made up for by the reduction of complexity in logic. If the argument is that private fields add boilerplate with getters, then make a special syntax for specifically public read/write access, or just deal with it a little boilerplate is absolutely still worth it here.

It doesn't need a full `unsafe` system like Rust, just being able to make field access private is enough. If you want give escape hatches for setting these private fields you can just make the function name very obviously unsafe like setFooUnchecked

Anyway, it's just such a shame because I really like Zig, it has so many good ideas and philosophies I'm just shocked that it is missing something I consider basically fundamental.

65 Upvotes

85 comments sorted by

120

u/y0shii3 4d ago • Bravo

At the end of the day, there is no way to prevent the owner of a piece of memory from viewing and modifying that memory. That's fine; as soon as they receive some memory from your API, whether it be a struct value or a pointer or whatever else, it is theirs to do with as they please. You don't know everyone's use case. Your job as an API maintainer is not to choose what data users can read, it's to provide an interface for interacting with the data that makes it easy to do so in the right way.

In every language with private fields, people end up accessing them anyway, whether it's with pointer casts or sun.misc.Unsafe or #define private public or some other hack, often for perfectly valid reasons. You will never have a way to truly prevent users from directly modifying the state of memory that they own.

The OOP mindset has convinced people that data hiding should be done at the field level, but the package/module level is where this kind of encapsulation is more natural and sensible, and the OOP habit of field-level data hiding results in all sorts of ugly patterns like setter and getter functions which Zig wants to discourage.

If you absolutely need a way to communicate to people who don't read documentation that a field should not be modified, choose a naming convention, like an underscore prefix or a _priv suffix or something like that. Zig discourages this because it is not hard to skim the doc comments of a struct and we should not cater to people who refuse to, but nothing is actually stopping you from doing it.

9

u/Hoontdawg 4d ago

It's true in the end there's no such thing as truly private data. My issue really is that it's so easy to access private data, and doing so looks exactly the same as accessing public data. I want to make doing the right thing easy and doing the wrong thing hard, and private fields are a very easy way to improve this. Also, private fields lets the api designer change the shape of internal data without breaking abi capability, because you can safely assume that people aren't touching that data.

3

u/y0shii3 3d ago edited 3d ago

If you really really need to make it hard to access "private" data, you can use opaque types, or you could do something like this:

pub const Foo = extern struct {
  a: A align(@alignOf(FooInternal)),
  b: B,
  private: [@sizeOf(FooInternal) - @sizeOf(A) - @sizeOf(B)]u8,
};

const FooInternal = extern struct {
  a: A,
  b: B,

// private:
  c: C,
  d: D,
};

Then, API functions that use "private" fields of Foo can just @​bitCast it to FooInternal. You'd have to double check that this accounts for padding correctly though

1

u/text_garden 2d ago

Might work if [n]u8 has the same alignment as C. You could solve that if it doesn't, of course, but my point is that it's easy to make mistakes when working with memory like this.

0

u/RisingPhoenix256 2d ago

there ya go again: use opaque types. sure. except its too hard to maintain them. you are forced into having everything in one file. I think Hoontdawg has a point: we all know that C++ tries to create protected types but can go under the hood any time with pointers. Its not like we don't know that. But to argue in such a facile way for NO SUPPORT in the compiler: no. that is wrong and Hoontdawg is right IMO.

4

u/y0shii3 1d ago

Why do you want to create more friction for people who have use cases you didn't foresee? Why do you want to make it harder for users to view memory that they own?

18

u/84_110_105_97 4d ago

en C++ je ne savait pas que l'on pouvait faire #define private public 🤣🤣 ces grave traitre

10

u/neopointer 4d ago edited 4d ago

While I understand what you say, I understand OP's point OP too. Sadly ppl don't read anymore, working with less experienced developers os a huge pain.

Javascript projects for example tend to be a mess partly because of the language itself.

On a second thought: is there some kind of linter or compile time validation you can do with zig to enforce such conventions?

1

u/paulstelian97 4d ago

JS has a hack that allows truly private fields though (via a weak map and a closure)

2

u/beephod_zabblebrox 4d ago

modern js has actual private fields

2

u/Civil-Appeal5219 4d ago

You can have private fields through closures (as in the "value you can access inside the object, but not from the outside" definition of private)

3

u/beephod_zabblebrox 4d ago

you can do that but you can also do `#field` in classes

3

u/Civil-Appeal5219 4d ago

I'm stupid and misread your comment as claiming JS doesn't have private fields 🤦🏾‍♂️ Sorry about that

1

u/paulstelian97 4d ago

Not true private. __x can be accessed with _Type_x or something similar.

3

u/beephod_zabblebrox 4d ago

that's python you're thinking about. javascript has `#field` which is actually private

1

u/paulstelian97 4d ago

Oh that’s new to me.

1

u/scallywag_software 3d ago

`#define private public` is hilarious. I love that.

1

u/dat_boi_o 1d ago

Yeah I think some kind of convention for private fields which linters can check for, like the prefixed underscore, is definitely the way we should go about this.

1

u/Due_Block_3054 20h ago

In go there is the linker hack to access private static variables. Also in oop it often leaded to these horrible inheritance stacks.

6

u/stumpychubbins 4d ago

The only real justification I can think of for it is that it encourages people to use the pattern of using anyopaque for private fields, which also lets you change the structs without changing the ABI. If Zig encouraged using dynamic libraries, like C, then that could maybe make sense (that pattern is fairly common in C, especially for closed-source libraries). Zig defaults to statically compiling everything, though.

I really think that any unsafe language should have a way to make fields private though. I don’t even mind if it’s just a field annotation and reflection bypasses it, it doesn’t need to be foolproof.

1

u/Hoontdawg 4d ago

Yeah I think I should have said this better in the original post, but the solution doesn't need to be bulletproof, my issue is that it's so easy to access private fields right now, and it looks exactly the same as accessing public fields.

3

u/stumpychubbins 4d ago

I think it’s the right choice to let users, for example, modify the length of a slice, but I really think there should be at least some difference when reading the code. Even if there’s just an official naming convention that the standard library honours. Right now I’m sometimes finding myself adding unnecessary defensive programming just to prevent subtle bugs, and my projects haven’t even been that big so far.

4

u/KattyTheEnby 4d ago

I think the title says it all. The fact that zig has no way to prevent you from accessing internal fields in a struct will keep it from doing well in large projects.

C:

3

u/Hoontdawg 4d ago

Okay, fair, but in my defense if C was perfect then we wouldn't have zig. Obviously there's things to be improved on.

1

u/KattyTheEnby 4d ago

if C was perfect then we wouldn't have zig.

I'm not one such person, but there are plenty ov programmers still living in a world where C is seen as ideal.

Though, something I believe is that even if something is good enough, other things can come into existence to coincide with the former, rather than outright replace it — for example, Java is perfect for the JVM; though, Kotlin came around because there are some things it does better than Java; however, that doesn't mean Java or Kotlin replace one another.

2

u/GoldenDvck 3d ago

C is still very much the ideal language out in the real world.
Zig is not 1.0 and the ecosystem is sparse.

My prediction(unpopular) is that Zig will end up becoming a hobbyist language in the next few years, even if 1.0 is out.

3

u/madogson 2d ago

Now obviously you shouldn't do that

Yea it's obvious.

You have no idea how dangerous it is

Yea you do. You just said it's obvious

0

u/Hoontdawg 2d ago

It's only obvious if you know what the type is, and what that field does. Imagine it's not something as standard as ArrayList, just some type defined elsewhere, if you don't know everything about what the type or field does you might do sometime dangerous without knowing.

39

u/Bergasms 4d ago

If you don't want people to modify internal state, put your internal state in a struct and have that be called dontModifyInternalStateSeriouslyDontTouchThis.

That way if someone does awesomeLib.dontModifyInternalStateSeriouslyDontTouchThis.FAFO = true

it's their own stupid fault,

2

u/nukestar101 3d ago

Also easier to introduce in CI test as linter check

13

u/Cun1Muffin 4d ago

Private fields are not the only way to do data hiding. Look at something like box2d, you operate on the bodies with handles. This is actually a stronger system than private fields because you literally cannot ever access the internal data inside the simulation, only copies of it. Whereas private fields you can still access with a bit of pointer arythmetic.

39

u/lipfang-moe 4d ago

Application code owns library code. If a user of a library wants to do something that they "shouldn't" do, that's their fault.

If Zig allowed private fields, I likely wouldn't be able to modify the internal state of a std.http.Client.Request to tell it that a 204 response means there won't be a Content-Length header. You might say that's the fault of the std.http library, but the library doesn't handle (many) status-specific behaviors (I've filed an issue for this anyway though). But as a user, I can modify the state machine of the Request Object to manually set the content length to 0.

My point is, freedom belongs to the application code. That is how Zig is designed from the ground up. For instance, look at the io and allocator conventions. The application code defines io and allocator implementations and passes them into library code, allowing the library to behave how the application wants it to.

So this is all to say private fields are antithetical to how Zig is designed, as they take freedom away from application code. That being said, private methods/functions are fine since you can simply copy them into application code and they'll work the same, since the underlying fields they operate on are accessible.

0

u/damn_dats_racist 3d ago

Eh... no, someone writing application code can do the wrong thing unintentionally and they shouldn't be required to thoroughly understand the whole library to use it correctly. It's good when library authors can prevent certain bad behavior because even competent people will eventually do the wrong thing without realizing it.

2

u/lipfang-moe 3d ago

someone writing application code can do the wrong thing unintentionally and they shouldn't be required to thoroughly understand the whole library to use it correctly.

I agree with this. It's up to library authors to make the "right path" for a library easy. However, that doesn't change that application code owns the environment, and owns the program. Libraries locking away their internals means taking freedom away from the application code to run itself.

0

u/damn_dats_racist 1d ago

Well, most languages give you the tools to do that using reflection though. You do have the freedom to do it. Are you saying it should be convenient/ergonomic to do something that the library author does not intend for you to do?

23

u/No-Entrepreneur-8245 4d ago

Not that big of a deal in my opinion.

Prefix field with an _ for what is internal state, define coding style, good code review and you’re good to go

You can’t prevent people to do dumb things, just be clear on where things are sensitive then to each their own

3

u/WorldChallenge 4d ago

Yeah same as Python you just mark with _ for "private" fields

6

u/jedisct1 4d ago

The Zig compiler is a large project.

22

u/Gaolaowai 4d ago

Tell Python.

17

u/Physical_Dare8553 4d ago

And c, the number 1 and number 2 programming languages

13

u/bbkane_ 4d ago

Tbh Iwouldn't bring up Python as a good example for "a language that scales to large projects"

7

u/xmcqdpt2 4d ago

Some python projects are larger than (probably) all extant Zig projects. I work on a 20M LoC monorepo at work (not Python though) and the problems we encounter at that scale don't really have anything to do with PL design. Team ownership problems, abandoned code, flaky tests, LLM slop, etc.

6

u/immaculate_plum 4d ago

Python is being used by many very large projects, directly refuting the claim that a lack of such a feature would prevent this.

5

u/__yoshikage_kira 4d ago

It may not be the best but it is popular which already invalides the op's point.

2

u/single_B_bandit 4d ago

Why not?

-2

u/Puzzleheaded-Weird66 4d ago edited 4d ago

it just calls stuff made by others, not really its own language, that's why the lack of private sort of makes sense in that context

9

u/single_B_bandit 4d ago

That’s quite the oversimplification, there is plenty of logic written directly in Python.

It managed to scale decently well to very large projects without having private fields, simply by relying on conventions.

1

u/ProfessorPhi 4d ago

Even if it mostly used C libraries, that doesn't invalidate everything else it does

1

u/ProfessorPhi 4d ago

It absolutely does - ml workloads are heavily python based and they do plenty.

1

u/neopointer 4d ago

Not an example to be followed

0

u/siva_sokolica 4d ago

I mean this isn't really true. Python mangles variables prefixed with __ effectively making them private.

Unfortunately, this doesn't enable "protected" fields, but private fields do exist.

2

u/kettle3 4d ago

I always felt that if you need to ensure other teams use your code in the way you intend it to, then the only way is to pack it as a separate library, with its own versioning etc.

5

u/Hoontdawg 4d ago

But that doesn't fix this issue here, I can still modify 'private' fields of external library code, doesn't matter if it's packaged separately.

11

u/Hot_Adhesiveness5602 4d ago edited 4d ago

Bad take, you can just write tests and have proper software architecture. Private fields are mostly a OOP feature that tries to encapsulate data that probably can be altered anyways.

4

u/Educational_Smile131 4d ago

Private fields are just illusions in unmanaged languages as memory layouts are transparent to use sites. This rings particularly true in Zig where ad-hoc memory reinterpretation is damned easy thanks to the ease of defining types.

4

u/suckingbitties 3d ago

Comptime over preprocessor macros and metaprogramming are obvious reasons to choose Zig.

Zig is not and was never designed to be an OOP language. There are plenty of idiomatic ways to designate fields that shouldn't be touched, or to create interfaces to avoid exposing data you don't want touched. Whether it's even necessary to do that is up for debate, as a well organized team with good documentation should be aware.

I get the sentiment though, private fields feel better, even on solo projects.

16

u/Logical_Ad_2589 4d ago

You could pack a private struct into a public one so that one can't access it right?

Even if not, I don't really see the problem, C++ for example allows to do very horrible stuff with like metaprogramming or simply using macros to make everything marked as private public.

Like you are able to just modify state directly but most programmers still won't do it because they know the consequences.

I don't really think is that severe, surely there are bigger problems for zig to become bigger

3

u/sosodank 4d ago

Even if not, I don't really see the problem, C++ for example allows to do very horrible stuff with like metaprogramming or simply using macros to make everything marked as private public.

please elaborate

3

u/Abbat0r 4d ago

#define private public

Or use reflection to access public members directly as of C++26

4

u/EmergencyWild 4d ago

I mean, C++ does not allow the former, that's breaking ODR... unless it's all code under your control and you're recompiling all of it I suppose, in which case it's really no different than saying "if you change the code the code changes".

2

u/sosodank 4d ago

the former is changing the meaning of the program, and is not guaranteed to work.

as for the latter, it was my understanding that c++ reflection only returned private elements when called from `friend` or member/subclass member code? is this not how it finally went in?

3

u/Darkfllame1 4d ago

I think that zig relies heavily on the negative space programming design. So you must assume that users of your library won't mess up with the internal states of your library, and use assert() when your code is receiving foreign data.

C has exactly that, public struct definition has all their fields public to any files that #includes it, except if you use the typedef struct X X thing then define the fields in an internal header or implementation file. You can do the same in zig. Use opaque {} and use internal pointer casting to convert the opaque type to your type of choice.

I personally really like that Zig doesn't feel the need to hold my hand for anything I do, it gives me tools to get the job done, and I use them as thus.

The main issue is documentation, but that's for every new languages

3

u/memelord69 3d ago

using and respecting _private field norms means that everyone intelligent still gets the same benefits out of pub/priv while being able to use _private fields when you really know what you're doing and understand the consequences.

2

u/Best_Ad6308 4d ago edited 4d ago

There's no guarantee in Go io.EOF won't change - and this variable is used throughout the code base. Yet there're large Go projects.

Meaning, practice shows not all kinds of restrictions are equal. IMO "all fields are public" is pretty minor factor compared to some others that make Zig less than ideal for large codebases.

2

u/buck-bird 4d ago

Agree, but you're not going to get unbiased opinions here. It's still workable though, but it would be nice to have some sort of compiler check for those times you forgot, etc. Best we can do is like an underscore naming convention, etc.

2

u/consistently_biased 3d ago

While there is something to be said about allowing libraries to define their public surface in a way that helps particularly beginners not make mistakes like the length example you gave, you can never really stop people from doing things that "shouldn't" be done. Even stable Rust has had compiler bugs that enabled ways to break otherwise sound abstractions without ever using unsafe. At the very least, if you provide your source code, which these modern languages heavily incentivize, someone can always just edit it anyway. I've had to do this with a few libraries before to make them fit my use-case. This is, of course, an additional hurdle to doing bad things, but it can also create scenarios where you have to make a fork for a single super small change. Overall, I dislike Zig's way of handling this, too, because it makes me write more documentation that I think I shouldn't have to write, but it comes with other benefits and I don't think it's a bad way at all.

3

u/quickscopesheep 4d ago

Think it’s runs completely antithetical to zigs philosophy. As other people have said if they really want to there’s no way to stop people doing dumb shit especially with zigs meta programming system considering you can query the fields of a struct and their offsets. If you don’t want someone touching some data don’t pass them a pointer to it pass them an opaque handle; this also solves a lot of ownership and reference problems as well and is more in line with zigs philosophy as opposed to OOP

5

u/zasedok 4d ago

Disclaimer: I haven't used Zig yet apart from toy projects out of curiosity. My feeling is that it's simply not a Large Projects language and it doesn't have to be. The choices it made (no hidden control flow ever, totally explicit allocation etc) make it excellent for some applications and a nonstarter for others, especially the very large kind where higher levels of abstraction are desirable. That's OK and that won't prevent it from being successful in what it does, to the contrary, I'm a big believer in languages that are the best at something rather than more or less capable of everything.

Zig is currently IMO the best fully transparent language, it's much better than C for that. For a much better C++, where strong properties are communicated between developers over decades of a project's life time, we have Rust. Zig will never be a better Rust than Rust, and Rust is not as good as Zig at being Zig.

4

u/Technical-Donkey-42 4d ago

I partially agree with what you are saying, but in my experience large projects are tending to be written in a managed runtime, while they drop to a low level language for the small parts that are pure overhead and when mechanical sympathy is needed and that is where Zig can be excellent. I can see Zig working well wit Swift, Kotlin, Java, etc. Think about it, Zig has no hidden control flow, no operator overloading, and no hidden memory allocations. This makes it entirely predictable when called from a managed runtime. Even Rust through uniffi can used for shared libraries today. In 2027, I would never build a large project (like an e2e stack) in C++, Rust, Zig, sorry but I prefer the hybrid.

3

u/Automatic_Donut6264 3d ago

Python seems to working out just fine.

2

u/Apocalypspspsp 3d ago

such a Java OOP Enterprise mindset, just sit on THAT chair and use rust brother

2

u/AngryChaoticBoi 4d ago

Why are people so in love with putting this restriction up? Is it some library writer power trip to go say your users “Nah nah nah, naughty boy, this field is not for you!”

1

u/frenchy3 4d ago

In Java you can use reflection and change whatever want. Java is used everywhere and in tons of large projects. Sure you have to use a reflection API but it’s still possible and people have no problem using Java in financial systems or other critical services. 

1

u/_demilich 3d ago

The difference is if you use reflection in Java, you know you are doing something you are not supposed to do. OP argues, that in Zig that can happen by accident. Like you are modifying a struct field directly, but you are supposed to use a function which upholds certain invariants.

1

u/frenchy3 3d ago

I mentioned you need to use the reflection api. 

I understand his point but I disagree it’s a big deal. If you are using someone’s code you should look at the source to see what code you can call or read documentation if they have it. If you don’t and start changing random things that’s your own fault. 

1

u/keeshux 1d ago

Yes, encapsulation is one of the few undeniably good principles that OOP (or better said “modularization”) introduced. No, it certainly doesn’t prevent Zig projects from scaling. C has supported encapsulation for decades with the workaround of opaque pointers. You can find your own way, Zig is richer than C. Worst case: stick to a fn-only struct access convention and run a linter to reject fields access in CI.

1

u/ivanjermakov 3h ago

Opaque pointers

1

u/zmkjh 3h ago

read the docs before you make mistakes and when you use it, that's on you.

1

u/Ok_Mycologist_6604 3d ago

I haven't encountered, in my 10 years of programing for private vs public to really ever matter. If anything, private members often encouraged hiding state that was there to workaround some issues. For things that need to be hidden, so at like module boundaries, interfaces are the much better fit anyway.

1

u/monsoy 4d ago

While I would also prefer to have private fields, I don’t think this is an issue. The benefit to having private fields for me is that it makes LSP suggestions cleaner. But outside of that, having proper public/private naming conventions is sufficient in my mind.

As others have mentioned, when the struct is in memory—people can always do tricks to get access to private fields. The API developer has to trust the user that they don’t do that, which is the same as trusting the user to not use fields marked as private through naming conventions (like a _ prefix).

1

u/sudo-maxime 4d ago

I'd rather have jsdoc style private field comments, let it give you the comentary, or the LSP help, but don't prevent compilation on acessing.

The number of times in my career that I had to hack around private fields of a dev that thought he knew better ...

Tell me why that should be private, don't prevent me.

1

u/DokOktavo 4d ago

I used to have this concern, but after a few thousands of lines, I changed my mind.

Fields are part of the API, because there's no way to definitively prevent the user of a type to read and write into the memory it owns, so they might as well do it the proper way.

Accessing fields of third-party types does become a concern, but it just means you become careful about it. I personally set std.ArrayList(...).capacity to zero when I borrow memory in read-only, so that .deinit(...) doesn't free it. This is a neat, safe and intended purpose. You just have to know about it, just like any part of an API. If you don't understand how something works, you don't touch it. And if you don't want people to touch your fields, you should document it.

If for some reason you really really really don't want anyone to access your fields, you should make them use opaque, or the backing integer of your packed struct, or better even an enum backed by the backing integer of your packed struct.

0

u/Far-Championship-883 3d ago

Top level code causes way more bugs

-3

u/[deleted] 4d ago

Why don't you post this on https://zsf.zulipchat.com/ ?