Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reasoning for #10 is wrong. #1

Closed
g-w1 opened this issue Feb 10, 2021 · 2 comments
Closed

Reasoning for #10 is wrong. #1

g-w1 opened this issue Feb 10, 2021 · 2 comments

Comments

@g-w1
Copy link
Contributor

g-w1 commented Feb 10, 2021

https://github.com/ratfactor/ziglings/blob/main/exercises/10_if2.zig#L12

Here you say the reason that it fails is that the compiler is not smart enough, but this is not true.
The error is

./main.zig:4:1: error: variable of type 'comptime_int' must be const or comptime
var i = if (true) 1 else 2;
^
./main.zig:2:29: note: referenced here
pub fn main() anyerror!void {
                            ^

The reason is that you cannot have a comptime_int variable in a non comptime scope. The compiler is smart enough to do peer type resolution.
For example, this works:

var b: bool = true;
var x = if (b) null else @as(u32, 5);
if (@TypeOf(x) != ?u32) @panic("OOF");

This example should be fixed and an explanation of peer type resolution should probably be made.

@ratfactor
Copy link
Owner

Thanks! This is exactly the kind of feedback I'm looking for. I'll correct it tonight.

ratfactor added a commit that referenced this issue Feb 11, 2021
It really has nothing to do with the if/else expression. The peer
types are being resolved correctly.  The same error can be produced
with something as simple as:

    var foo = 5;
@ratfactor
Copy link
Owner

@g-w1 I wrote up a whole new comment before I realized the entire issue should be ignored at this stage - I've removed the fallacious explanation and the warning. Until now, we've been doing the right thing (giving types to all integer vars).

Peer resolution is working correctly in this expression, as you mentioned. I'll probably need to add at least one exercise later that will bring the issue up properly in its own context!

Thanks again for spotting this. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants