| ... | ... | @@ -7533,19 +7533,21 @@ export fn @"A function name that is a complete sentence."() void {} |
| 7533 | 7533 | |
| 7534 | 7534 | {#header_open|@field#} |
| 7535 | 7535 | <pre>{#syntax#}@field(lhs: anytype, comptime field_name: []const u8) (field){#endsyntax#}</pre> |
| 7536 | | <p>Performs field access by a compile-time string. |
| 7536 | <p>Performs field access by a compile-time string. Works on both fields and declarations. |
| 7537 | 7537 | </p> |
| 7538 | 7538 | {#code_begin|test#} |
| 7539 | 7539 | const std = @import("std"); |
| 7540 | 7540 | |
| 7541 | 7541 | const Point = struct { |
| 7542 | 7542 | x: u32, |
| 7543 | | y: u32 |
| 7543 | y: u32, |
| 7544 | |
| 7545 | pub var z: u32 = 1; |
| 7544 | 7546 | }; |
| 7545 | 7547 | |
| 7546 | 7548 | test "field access by string" { |
| 7547 | 7549 | const expect = std.testing.expect; |
| 7548 | | var p = Point {.x = 0, .y = 0}; |
| 7550 | var p = Point{ .x = 0, .y = 0 }; |
| 7549 | 7551 | |
| 7550 | 7552 | @field(p, "x") = 4; |
| 7551 | 7553 | @field(p, "y") = @field(p, "x") + 1; |
| ... | ... | @@ -7553,6 +7555,15 @@ test "field access by string" { |
| 7553 | 7555 | expect(@field(p, "x") == 4); |
| 7554 | 7556 | expect(@field(p, "y") == 5); |
| 7555 | 7557 | } |
| 7558 | |
| 7559 | test "decl access by string" { |
| 7560 | const expect = std.testing.expect; |
| 7561 | |
| 7562 | expect(@field(Point, "z") == 1); |
| 7563 | |
| 7564 | @field(Point, "z") = 2; |
| 7565 | expect(@field(Point, "z") == 2); |
| 7566 | } |
| 7556 | 7567 | {#code_end#} |
| 7557 | 7568 | |
| 7558 | 7569 | {#header_close#} |