conststd=@import("std");constbuiltin=@import("builtin");test"confirm OS type"{constis_windows=builtin.os.tag==.windows;std.debug.print("is windows = {}\n",.{is_windows});constis_mac=builtin.os.tag==.macos;std.debug.print("is mac = {}\n",.{is_mac});constis_linux=builtin.os.tag==.linux;std.debug.print("is linux = {}\n",.{is_linux});std.debug.print("this os is {}\n",.{builtin.os.tag});}
usingnamespace
namespace is struct, union, enum or opaque in Ziglang. (see document).
You can use pub functions and declarations in the namespace. You can't use ones without pub.
You can use it like mixin.
conststd=@import("std");consttesting=std.testing;test"usingnamespace"{constS=struct{usingnamespace@import("std");/// this property does not become a member in caller struct due to lack of `pub`constNOT_IN_NAMESPACE_NUM=11;/// this property becomes a member with usingnamespace.pubconstNUM=12;/// this property does not become a member in caller struct due to lack of `pub`fnnotInNamespaceFunc()bool{returnfalse;}/// this property becomes a member with usingnamespace.pubfninNamespaceFunc()bool{returntrue;}};// caller struct for S.constT=struct{usingnamespaceS;};// usingnamespace T; // this statement can not be compiled.// you can use all members from S scope.tryS.testing.expect(true);tryS.testing.expectEqual(S.NOT_IN_NAMESPACE_NUM,11);tryS.testing.expectEqual(S.NUM,12);trytesting.expect(!S.notInNamespaceFunc());trytesting.expect(S.inNamespaceFunc());// you can use only members with pub in S from T scope.// try testing.expectEqual(T.NOT_IN_NAMESPACE_NUM, 11); // this statement can not be compiled.trytesting.expectEqual(T.NUM,12);// try testing.expect(!T.notInNamespaceFunc()); // this statement can not be compiled.trytesting.expect(T.inNamespaceFunc());}
How to handle command-line args
How to use the following code:
with building:
e.g. for building: $ zig build-exe main.zig -O Debug
e.g. for executing: $ ./main.exe arg1 arg2
with run command:
e.g. $ zig run main.zig -- arg1 arg2
conststd=@import("std");constprocess=std.process;constArgs=struct{constSelf=@This();allocator:std.mem.Allocator,items:[][:0]u8,pubfninit(allocator:std.mem.Allocator)!Args{returnArgs{.allocator=allocator,.items=tryprocess.argsAlloc(allocator),};}pubfndeinit(self:Self)void{deferprocess.argsFree(self.allocator,self.items);}pubfnprint(self:Self)void{for(self.items)|item,i|{std.debug.print("arg[{d}]={s}\n",.{i,item});}}};pubfnmain()!void{vargpa=std.heap.GeneralPurposeAllocator(.{}){};constallocator=gpa.allocator();deferstd.debug.assert(!gpa.deinit());constargs=tryArgs.init(allocator);deferargs.deinit();args.print();// how to access individual argumentsfor(args.items)|item,i|{std.debug.print("args[{d}] from props={s}\n",.{i,item});}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)