langref: delete misleading example code about packed structs
Some checks failed
ci / x86_64-linux-debug (push) Has been cancelled
ci / x86_64-linux-release (push) Has been cancelled
ci / aarch64-linux-debug (push) Has been cancelled
ci / aarch64-linux-release (push) Has been cancelled
ci / x86_64-macos-release (push) Has been cancelled
ci / aarch64-macos-debug (push) Has been cancelled
ci / aarch64-macos-release (push) Has been cancelled
ci / x86_64-windows-debug (push) Has been cancelled
ci / x86_64-windows-release (push) Has been cancelled
ci / aarch64-windows (push) Has been cancelled

This commit is contained in:
Andrew Kelley 2024-11-13 15:35:16 -08:00
parent 4fc295dc02
commit bfcf18c5a7

View File

@ -6,28 +6,13 @@ const Point = struct {
y: f32,
};
// Maybe we want to pass it to OpenGL so we want to be particular about
// how the bytes are arranged.
const Point2 = packed struct {
x: f32,
y: f32,
};
// Declare an instance of a struct.
const p = Point{
const p: Point = .{
.x = 0.12,
.y = 0.34,
};
// Maybe we're not ready to fill out some of the fields.
var p2 = Point{
.x = 0.12,
.y = undefined,
};
// Structs can have methods
// Struct methods are not special, they are only namespaced
// functions that you can call with dot syntax.
// Functions in the struct's namespace can be called with dot syntax.
const Vec3 = struct {
x: f32,
y: f32,
@ -46,7 +31,6 @@ const Vec3 = struct {
}
};
const expect = @import("std").testing.expect;
test "dot product" {
const v1 = Vec3.init(1.0, 0.0, 0.0);
const v2 = Vec3.init(0.0, 1.0, 0.0);
@ -67,14 +51,14 @@ test "struct namespaced variable" {
try expect(Empty.PI == 3.14);
try expect(@sizeOf(Empty) == 0);
// you can still instantiate an empty struct
const does_nothing = Empty{};
// Empty structs can be instantiated the same as usual.
const does_nothing: Empty = .{};
_ = does_nothing;
}
// struct field order is determined by the compiler for optimal performance.
// however, you can still calculate a struct base pointer given a field pointer:
// Struct field order is determined by the compiler, however, a base pointer
// can be computed from a field pointer:
fn setYBasedOnX(x: *f32, y: f32) void {
const point: *Point = @fieldParentPtr("x", x);
point.y = y;
@ -88,8 +72,7 @@ test "field parent pointer" {
try expect(point.y == 0.9);
}
// You can return a struct from a function. This is how we do generics
// in Zig:
// Structs can be returned from functions.
fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
@ -105,8 +88,7 @@ fn LinkedList(comptime T: type) type {
}
test "linked list" {
// Functions called at compile-time are memoized. This means you can
// do this:
// Functions called at compile-time are memoized.
try expect(LinkedList(i32) == LinkedList(i32));
const list = LinkedList(i32){
@ -139,4 +121,6 @@ test "linked list" {
// instead of try expect(list2.first.?.*.data == 1234);
}
const expect = @import("std").testing.expect;
// test