6 ms·
Zig's (.{}){} Syntax
- kristoff_it 2y agoAs people have pointed already elsewhere, the same declaration can be made more clear by isolating the type like so: var gpa: std.mem.GeneralPurposeAllocator(.{}) = .{};
- declan_roberts 2y agoAh yes. Much more clear. Thank you.
- mlugg 2y agoAlso note that on Zig master, initializing `GeneralPurposeAllocator` like this is deprecated -- it'll be removed after the next release. Instead, you should do this: var gpa: std.mem.GeneralPurposeAllocator(.{}) = .init;
- kcbanner 2y agoAfter you've been writing zig for a while, seeing `.{}` in an argument list intuitively means "default arguments".
- dleslie 2y agoSeems like it could just be elided entirely. Why can't it be?
- samatman 2y agoFor the same reason you can't pass a Python function expecting a list an empty list with foo(), you have to use foo([]). They mean different things.
- owl57 2y agoI believe that if most foo's users should just call it with [], the Pythonic way is to make the argument optional.
- samatman 2y agoWell yes, but if it's someone else's library, realistically you're not going to change it. Zig is a static language without variadic parameters, so you can't make it optional in that sense. You could make the options a `?T` and pass `null` instead, but it isn't idiomatic, because passing `.{}` to a parameter expecting a `T` will fill in all the default values for you.
- xigoi 2y agoThis doesn’t answer the question why Zig doesn’t have default argument values.
- throwawaymaths 2y agoDefault argument variables create variadic functions. Arity N when you supply a value Arity N-1 when you use the default
- xigoi 2y agoOkay, but why could a static language not have variadic functions?
- throwawaymaths 2y agoThat's their design choice. I can think of a few reasons - makes function calling simpler - faster compilation - less symbol mangling - makes grepping for function implementation easier If for some reason you think you absolutely can't live without variadic functions, maybe don't use zig.
- 2y ago
- Veserv 2y agoI do not know Zig, but it looks like it just means "call default constructor for parameter/variable/type". I do not see how you could expect it to be elided unless every function auto-constructs any elided arguments or always has default arguments. In other words, for a function f(x : T), f(.{}) is f(T()), not f(), where T() is the default constructor for type T. If we had a function with two parameters g(x : T, y : T2) it would be g(.{}, .{}) which means g(T(), T2()), not g(). It looks like the feature exists to avoid things like: x : really_long_type = really_long_type(), which can be replaced with x : T = .{} to avoid unnecessary duplication.
- dleslie 2y agoI do not know Zig either; I had assumed that it has default parameters, but it seems that it does not[0]. So, yes, it makes sense now why it cannot be elided. They should add default parameters to avoid this sort of thing. Maybe they ought to consider named/labelled parameters, too, if they're so concerned about clarity. 0: https://github.com/ziglang/zig/issues/484 https://github.com/ziglang/zig/issues/484
- AlienRobot 2y agoDeclaring a variable doesn't initialize it in Zig, so maybe the correct semantics in ellisions would be to allocate an unitialized argument.
- drcode 2y agoZig believes that all code needs to be explicit, to prevent surprises- You never want code that "just executes on its own" in places you may not expect it. Therefore, if you want default arguments, you have to perform some action to indicate this.
- dleslie 2y agoExcept it's not entirely explicit. It allows the type name of the object being constructed to be elided. Per the article, this is the explicit form: var gpa = std.heap.GeneralPurposeAllocator(std.heap.GeneralPurposeAllocatorConfig{}){};
- superb_dev 2y agoI don’t think type elision make the codes execution less explicit. Nothing else could go there
- necovek 2y agoThat's a textbook definition of "implicit", as in not directly specified, but assumed. The fact that unacceptable parameter would fail compile time validation does not make it any more readable.
- dleslie 2y agoConsider this: var foo = OpaqueTypeName(.{}){}; What is the . eliding? You don't know. I don't know. It's impossible to tell because the type is opaque to our understanding.
- deleted 2y ago[deleted]
- cztomsik 2y agoexplicit about branching and allocations, not so for types. we've recently got .decl() syntax, which is even more implicit than .{}
- 2y ago
- em-bee 2y agoi have never used zig before, but after reading the article i came to the same conclusion. the "problem" (if it is a problem at all, that is) really is that .{} is the syntax for a struct whose type is to be figured out by the compiler, that new users will be unfamiliar with. i don't know if there are other uses for . and {} that would make this hard to read. if there are, then maybe that's an issue, but otherwise, i don't see that as a problem. it's something to learn. ideally, each syntax element has only one obvious use. that's not always possible, but as long as the right meaning can easily be inferred from the context, then that's good enough for most cases.
- samatman 2y agoOne will quickly become accustomed to the .{} pattern learning Zig. It's used for struct constructors: const a_struct: StructType = .{ .foo = "baz"}; As well as union initialization. So .{} is a struct constructor for a struct where every field has a default value, which chooses all of those fields.
- flohofwoe 2y agoI think it becomes clearer when considering that these are all equivalent: const a_struct: StructType = StructType{ .foo = "baz" }; const a_struct = StructType{ .foo = "baz" }; const a_struct: StructType = .{ .foo = "baz" };
- flohofwoe 2y ago> that new users will be unfamiliar with It's really not much different than in nearly any other language with type inference except for the dot (which is just a placeholder for an inferred type name).
- selfmodruntime 2y agoA whole lot of cleverness for a language that refuses to compile when you have unused parameters.
- conradev 2y agoWith the Zig language server it’s not terribly annoying: _ = foo; // autofix
- AlienRobot 2y agoAnd has no multi-line comments.
- MineBill 2y agoIf you want to see true cleverness just go see the last devlog on the zig website.
- mtlynch 2y agoI think this is the post parent is referencing: https://ziglang.org/devlog/2024/#2024-11-04 https://ziglang.org/devlog/2024/#2024-11-04 It seems like an interesting idea, but I wish Andrew spent more time fleshing it out with complete examples. I can't tell if the _ characters are eliding values or if that's literally what's in his code.
- defen 2y agoIt's Zig's equivalent of the newtype idiom: https://doc.rust-lang.org/rust-by-example/generics/new_types.html https://doc.rust-lang.org/rust-by-example/generics/new_types... for integers. The underscores mean that it's a non-exhaustive enum. An exhaustive enum is where you list all the names of the possible enum values, and other values are illegal. A non-exhaustive enum means any value in the underlying storage is allowed. So at root this code is creating a bunch of new integer types which are all backed by u32 but which can't be directly assigned or compared to each other. That means you can't accidentally pass a SectionIndex into a function expecting an ObjectFunctionImportIndex, which would be impossible to do if those functions just took raw u32's.
- andout_ 2y agoThe article spends a lot of time justifying a syntax that really just papers over Zig's lack of parameter pack support. The same pattern in Rust would just use variadic templates/generics.
- samatman 2y agoThis comment might be valuable if you added some elaboration, and an example of what it looks like.
- fallingsquirrel 2y ago> The same pattern in Rust would just use variadic templates/generics. Are you sure Rust has variadic generics? Last I checked, the extent of progress was a draft RFC. https://github.com/rust-lang/rfcs/issues/376 https://github.com/rust-lang/rfcs/issues/376
- steveklabnik 2y agoTo be super clear: it does not.
- deleted 2y ago[deleted]
- PoignardAzur 2y ago> The same pattern in Rust would just use variadic templates/generics. Man, must be nice to be a time traveler from the 2030s. How does Covid25 turn out?
- samatman 2y agoI'm glad I read the last line, for those who may not have gotten that far: this is about to become a much less prevalent pattern in Zig code, replaced with declaration literals. The new syntax will look like this: var gpa: std.mem.GeneralPurposeAllocator(.{}) = .init; Which finds the declaration literal `std.mem.GeneralPurposeAllocator.init`, a pre-declared instance of the GPA with the correct starting configuration.
- kvark 2y agoThat “.” substitution of an inferred type is going to fire back. I really appreciate when code has one simple property: you search a type by name and you get all of the places where it’s constructed. Makes it easy to refactor the code and reason about it with local context. It’s the case with Rust, but not C++ or Zig.
- zamadatix 2y agoWhat's meaningfully different in Rust's type inference. E.g.: fn example() { let p = returns_a_point_type(args); } Where create_point() is a function from a module (e.g. not even defined in that file) which returns the Point type automatically inferred for p? I mean sure, it's technically constructed in the called function... but is that often a useful distinction in context of trying to find all of the places new instances of types are being assigned? In any case, this is something the IDE should be more than capable of making easier for you than manually finding them anyways.
- nindalf 2y agoGP is talking about how easy it is to find places where the type is instantiated. Seems to me that create_point() will have one such site. And then it’s trivial to find callsites of create_point() with the LSP/IDE. What’s the issue?
- zamadatix 2y agoThe IDE can find all places new variables are assigned to the type (regardless of whether it's direct instantiation, return value, inferred, or whatever way it comes about) so what's the special value of being able to manually find only the local instantiations find ctrl+f if you'd still need to manually track down the rest of the paths anyways?
- int_19h 2y agoAny IDE worth its salt will let you search a type by name and get all the places where it's referenced, regardless of type inference.
- kazinator 2y agoIt's amazing they couldn't figure out how to get f(.{}) down to just f({}). Like here is this brace enclosed thing being matched against the argument type.
- 8n4vidtmkvmk 2y agoThat's how it is in c++ so I'm used to it now, but I don't think I mind the dot. It differentiates a block scope from a struct initializer.
- akira2501 2y agoIn C's grammar you would need to wrap the {} as ({}) in order to get into a block expression scope from an argument list.
- kazinator 2y agoThat's GNU C, not standard C. Standard C has no such feature as blocks being expressions. Compound literals are grotesque. The braces have to be proceeded by cast syntax indicating the type. It could be subject to inference. Maybe the current draft has something.
- danhau 2y agoI actually find compound literals quite pleasing, visually. Parentheses, brackets and braces I find can help a lot in guiding your eyes though code. They make it more „regular“, or lessen the „entropy“ (physicists, please don‘t stone me). For this reason I‘ve come to dislike Rust’s braceless if-syntax, after being a die-hard fan. With parentheses it just reads better.
- flohofwoe 2y agoC99 has compound literals which allows you to call functions that take struct values or pointers to structs like this: my_func((my_type){ .x = 1, .y = 2 }); my_func(&(my_type){ .x = 1, .y = 2 });
- ninepoints 2y agoUsing parens to pass type arguments was one of the things that turned me off on Zig. For a language that prioritizes "no hidden control flow," it sure did a lot to make various syntax conventions _masquerade_ as control flow instead.
- codethief 2y agoWhat do you mean? It is control flow. Generic functions are just higher-order functions that get evaluated at compile time.
- cobbal 2y agoIt is an interesting question of definitions. Is control flow only at runtime? Is `#if` control flow in C? If I had to define it, I would go with runtime-only, but I could see the other way too.
- superb_dev 2y agoZig’s comptime is just code that runs at compile time. Unless we have another term, we must call it control flow
- strogonoff 2y agoMacros can have control flow, so compile-time control flow is definitely possible, but perhaps we trained ourselves to not think of control flow in this way because using complicated compile-time logic is generally frowned upon as a footgun. Perhaps Zig is the language that on purpose blurs the line between what runs when (by basically having what looks like macros integrated into runtime code without any conspicuous hashtaggy syntax), and so a Ziggy would not see compile-time control flow as something weird.
- ninepoints 2y ago[flagged]
- 2y ago
- NoelJacob 2y agoWhy did they keep the dot in Struct initialisation? Why not the syntax of just using without dot: const c1 = Config{ port = 8000, host = "127.0.0.1", }; Is there some other use with dotless one?
- throwawaymaths 2y agoBecause your type name might be std.foo.bar.baz.quux.Config
- thezipcreator 2y agoJust `{}` means a code block; in Zig you could do something like const c = blk: { const x = 5; break :blk x-3; }; // c = 2 just having an empty block `{}` is exactly that—an empty block of type `void`. having a dot or something else distinguishing it from a block is necessary in order for it to not be that.
- flohofwoe 2y agoIn many situations the compiler can infer the type: fn my_func(): MyType { return .{ ... }; } The dot is just the placeholder for the inferred type and the above is equivalent with: fn my_func(): MyType { return MyType{ ... }; } ...and Zig allows to write that verbose form too if you prefer that.
- indulona 2y agofugly syntax is one of the biggest reasons i will never touch rust. zig is not far too off, unfortunately. i i needed non-gc language, i would go for odin. not perfect but closes to usable. it's just too hard to do anything but Go, once you get comfortable with it. they got too many things right to see grass being greener elsewhere.
- IshKebab 2y agoRust encodes far more information into source code than most languages, so it simply needs more syntax. I wouldn't say it's ugly (except macros, not sure what they were thinking there), there's just more of it. Obviously if you remove lifetimes, types, references, etc. you're going to need less syntax.
- indulona 2y agojust because there are more keywords/syntax, it does not necessarily mean it has to be ugly. they could have made better decisions when designing the language.
- bmacho 2y ago> Rust encodes far more information into source code than most languages, so it simply needs more syntax. I don't think this is the case. Firstly, all the necessary data can be encoded by keywords, spaces and newlines. Forth or TCL can encode everything Rust can (since their interpreters are 100% configurable), only with keywords, and spaces between. A language should have special syntax for only the important part, not for everything. Secondly, even though Rust has special syntax for a lot of stuff, it could be nicer to the eye. For example, RattleSnake here https://matklad.github.io/2023/01/26/rusts-ugly-syntax.html https://matklad.github.io/2023/01/26/rusts-ugly-syntax.html or "Haskell flavored Rust" here https://news.ycombinator.com/item?id=34541695#34543124 https://news.ycombinator.com/item?id=34541695#34543124 are much nicer to the eye. But if you need a bunch of stuff that may or may not apply to a function or type definition for example, then why not just use CSS/Rebol style syntax, and put all your keywords that apply in a row. No need for all the weird symbols, brackets, colons and all that. You could even use keyword=no, and be extra explicit.
- kunley 2y agoEven more unfriendly-yet-typical line is where you create an allocator, and few lines further you run allocator() method on it, to get ...an allocator (but you had it already! Or maybe you didn't ?) Same: you create Writer, but then you run a writer() method on it. Here is the code to illustrate: var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var visited = std.BufSet.init(arena.allocator()); var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); const stdout = bw.writer(); So.. what are the entities we use, conceptually? "allocatorButNotReally" and "thisTimeReallyAnAllocatorIPromise"? Same for the writer? Plus, the documentation isn't much explaining wtf is this and why. The answer is probably buried somewhere in forums history, blogs and IRC logs, because there must have been consensus established why is it ok to write code like that. But, the lack of clear explanation is not helping with casual contact with the language. It's rather all-or-nothing - either you spend a lot of time daily in tracking all the media about the ecosystem, or you just don't get the basics. Not good IMO. (and yes I like a lot about the language).
- kristoff_it 2y agostd.mem.Allocator is the allocator interface. For that struct to be considered an interface, it must not contain directly any specific concrete implementation as it needs to be "bound" to different implementations (GenealPurposeAllocator, ArenaAllocator, ...), which is done via pointers. An allocator implementation holds state and implements alloc, free and resize for its specific internal mechanisms, and then pointers to all these things are set into an instance of std.mem.Allocator when you call the `.allocator()` function on an instance of an allocator. https://ziglang.org/documentation/master/std/#std.mem.Allocator https://ziglang.org/documentation/master/std/#std.mem.Alloca... File and Socket both offer a `.writer()` function to create a writer interface bound to a specific concrete "writeable stream". BufferedWriter has both extra state (the buffer) and extra functions (flush) that must be part of a concrete implementation separate from the writer interface. > The answer is probably buried somewhere in forums history That's just how computers work, languages that don't expose these details do the same exact thing, they just hide it from you.
- Aeolun 2y ago
- xg15 2y agoI'm actually more puzzled about the infinite recursion in this type function: fn Node(T: type) type { return struct { value: T, next: ?*Node(T) = null, }; } In other languages, defining types in terms of themselves is unproblematic, because the type identifier is just a symbol and the whole thing amounts to a graph with a backreference. However, here it's supposed to represent actual executable code, which is run by the compiler and "produces" a type in the end. But how would the compiler execute this function without getting stuck in a loop?
- throwawaymaths 2y agoThat seems wrong? For exactly the reason you say. The correct code, I would guess, should be `@This()` However, I also wouldn't be surprised if somehow the memoization in the zig compiler makes this ok