最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Zig unable to evaluate comptime expression - Stack Overflow

programmeradmin3浏览0评论

I'm trying to learn Zig using the website /. I was solving this exercise, which requires us to find the nth prime number.

My idea was to generate all of them during comptime and return as required; this is my current my code:

const std = @import("std");
const mem = std.mem;

const buffer_size = 100000;

fn sieve(comptime buffer: []usize, comptime limit: usize) []usize {
    if (limit < 2)
        return buffer[0..0];
    const sqrt_limit = std.math.sqrt(limit);
    var bitset = std.StaticBitSet(limit + 1).initFull();
    var n: usize = 3;
    var i: usize = 1;
    
    
    buffer[0] = 2;
    while(n <= sqrt_limit): (n += 2) {
        if (!bitset.isSet(n))
            continue;

        buffer[i] = n;
        i += 1;
        var j = 2 * n;
        while (j <= limit): (j += i) {
            bitset.unset(j);
        }
    }
    while (n <= limit) : (n += 2) {
        if (!bitset.isSet(i))
            continue;

        buffer[i] = n;
        i += 1;
    }
    return buffer[0..i];
}


var primes_buffer: [buffer_size]usize = undefined;
const primes = sieve(&primes_buffer, buffer_size);

pub fn prime(allocator: mem.Allocator, number: usize) !usize {
    _ = allocator;
    return primes[number-1];
}

But when I try to compile this, I'm getting the following error:

nth_prime.zig:15:15: error: unable to evaluate comptime expression
nth_prime.zig:15:11: note: operation is runtime due to this operand
nth_prime.zig:39:21: note: called from here

Why am I not able to populate my array at comptime, and why is this line problematic?

buffer[0] = 2;
发布评论

评论列表(0)

  1. 暂无评论