Solution to most recent ziglings 074?

Sorry, I’m trying to learn by doing, and I can’t figure out 074.
Does anyone have any solutions for that one?

All the information should be in the previous exercises.

What are you stuck on?

I figured that the needed change was adding the state being set to .start?
(Edit: I also fixed the gator compile time error that they hinted they wanted, but that doesn’t seem to apply to this)

// Something is missing here. After we finish a Llama, we
// need to be ready to _start_ over with a new animal...
state = .start;

Still gives me:
error: Only llamas start with ‘l’!

You might want to continue reading the code after that function

Hint: The problem is described in the main function.

Spoiler: An alternate solution

Another possible fix is to wrap the entire function body in a comptime block (and drop the inline from the for):

fn makeCreature(comptime count: usize, comptime fmt: []const u8) [count]Animal {
    return comptime blk: {
        var animals: [count]Animal = undefined;
        // ...

        break :blk animals;
    }
}

This is the approach that stuff like std.unicode.utf8ToUtf16LeStringLiteral uses

2 Likes

I did read the stuff about using @compileLog to see the comparison to runtime variables … but I’m still lost on comptime …

That’s a neat way to solve it.

The comments in main explained the problem and gave a solution

2 Likes

“this makeCreature call will still only succeed if you move it outside of main”

The more important bit is this:

    // You can solve this by adding "comptime" to two of the variables in
    // makeCreature...
Spoiler

The variables that would need to be marked comptime are state and next_animal since you need comparisons against them to run at comptime in order to avoid the compile errors being triggered.

Hopefully that gives context for the “alternate solution” I posted above.

(maybe also worth noting that adding comptime to call site would have the same effect as moving the call outside of main, e.g. const creature = comptime makeCreature(2, "mlm");)

the important part is

// With the call here, Zig will try to make the creature at runtime, and
// you'll get an interesting error.
//
// You may think the state got mixed up, but if you use @compileLog to check
// some variables in makeCreature, you'll see that Zig is trying to compare
// comptime values with "[runtime value]", which will never match.

Which is the problem, and how you might’ve discovered it.