0

I'm working on a small text adventure as a way to practice Zig. In it, I want the player to be able to move from one Location to another, with the locations stored within the World Map. While I can add a line to Main that accomplishes what I'm trying to do, trying to add a function to the World Map struct will not compile.

pub const WorldMap = struct {
    currentLocation: *const Location = undefined,
    locations: []const Location,

    pub fn setLocation(self: WorldMap, loc: *Location) void {
        self.currentLocation = &loc;
    }

    pub fn printLocationBrief(self: WorldMap) void {
        self.currentLocation.print();
    }

    //TODO: Add method for traversing from the current location to a new one.
    //pub fn travelToFirstConn(self: WorldMap) void {
    //    self.currentLocation = self.currentLocation.connections[0].dest;
    //}
};

The commented out section will not compile. Meanwhile if I add essentially the same line in Main...

    try stdout.print("Testing first move...\n", .{});
    Map.currentLocation = Map.currentLocation.connections[0].dest;
    Map.printLocationBrief();

It works just fine. Why?

  • Possible duplicate of [How do I mutate a Zig function argument?](https://stackoverflow.com/questions/74021886/how-do-i-mutate-a-zig-function-argument). – sigod Aug 08 '23 at 03:12

2 Answers2

1

Function parameters are immutable in Zig. Also, struct methods are not special, they are only namespaced functions that you can call with dot syntax.

You need to pass a pointer to the struct to be able to modify the struct:

fn travelToFirstConn(self: *WorldMap) void
sigod
  • 3,514
  • 2
  • 21
  • 44
0

I've found an answer.

 //TODO: Add method for traversing from the current location to a new one.
pub fn travelToFirstConn(self: *WorldMap) void {
    self.currentLocation = self.currentLocation.connections[0].dest;
}

This seems to work, after replacing the line of code in Main with:

try stdout.print("Testing first move...\n", .{});
Map.travelToFirstConn();
Map.printLocationBrief();

The key difference seems to be assigning Self in the function method as a pointer to itself, instead of simply self. Which seems to be a copy of the definition of the struct itself. I suppose as long as the actual instantiated struct is a var, this should work in general.