Hello, I’m going through Ziglings to try to learn this language. I thought I would just start learning with advent of code, but it’s broken my brain hard enough that I needed something a little more guided.
I’m on 47 and 48_methods2 trying to understand the pointer/reference syntax.
First question, I took Elephants from 48 and instead of pointers wanted to pass in the struct to see if it cloned the object.
const std = @import("std");
const Elephant = struct {
letter: u8,
tail: ?*Elephant = null,
visited: bool = false,
// New Elephant methods!
pub fn getTail(self: Elephant) Elephant {
return self.tail.?; // Remember, this means "orelse unreachable"
}
pub fn hasTail(self: Elephant) bool {
return (self.tail != null);
}
pub fn visit(self: Elephant) void {
self.visited = true;
}
pub fn print(self: Elephant) void {
// Prints elephant letter and [v]isited
const v: u8 = if (self.visited) 'v' else ' ';
std.debug.print("{u}{u} ", .{ self.letter, v });
}
};
pub fn main() void {
var e = Elephant{ .letter = 'A' };
e.visit();
std.debug.print("eleelements {any}\n", .{e});
}
But instead I get a bizarre constant error
elephants.zig:18:13: error: cannot assign to constant
self.visited = true;
~~~~^~~~~~~~
What did I do? What made it constant?
Second question, in 47, I can’t understand this line
for (&aliens) |*alien| {
Why do I have to iterate over a reference to the array, when you don’t have to do that with strings, or []u8
? And what does *alien
mean? My C brain tells me that it’s a pointer, but I didn’t think you could change what you were capturing, you just captured whatever was being iterated over.
I’ve tried changing it to this:
for (aliens) |alien| {
heat_ray.zap(&alien);
But now I get a compile error that I’m not mutating the aliens array???
So, on the one hand, if I pass in the struct, no pointers, it’s a constant, and I need it to be mutable. But on the other, I can pass in a reference to a method that mutates and now I’m not mutating.
Please help.