#Make a generic `type` in a struct recognize a method from another struct

1 messages · Page 1 of 1 (latest)

waxen phoenix
#

I am getting the following error. Am I doing this in the wrong way in zig?

error: no field or member function named 'get_sample' in 'oscillator.SineWave'

const std = @import("std");
const tau = std.math.tau;

pub fn Oscillator(comptime W: type) type {
    return struct {
        phase: f32,
        phase_step: f32,
        wave_type: W,

        const Self = @This();

        pub fn init(phase: f32, phase_step: f32, wave_type: W) Oscillator(W) {
            return Oscillator(W){
                .phase = phase,
                .phase_step = phase_step,
                .wave_type = wave_type,
            };
        }

        pub fn next_phase(self: *Self) void {
            const v = self.phase + self.phase_step;
            self.phase = v - @trunc(v);
        }

        pub fn get_sample(self: *Self, amp: f32) f32 {
            return self.wave_type.get_sample(self.phase, amp);
        }
    };
}

pub const SineWave = struct {
    pub fn get_sample(phase: f32, amp: f32) f32 {
        return amp * @sin(phase * tau);
    }
};

pub fn main() void {
    const sine_wave = oscillator.SineWave;
    var a = oscillator.Oscillator(oscillator.SineWave).init(0, 0.25, sine_wave{});
    a.next_phase();
    std.debug.print("Number: {}\n", .{a.get_sample(1)});
}

frozen arrow
#

since get_sample doesn't take a self parameter, you have to call it on the type rather than on instances of the type

#

like you can do SineWave.get_sample(...)

waxen phoenix
#

But how to do it while keeping the oscillator generic? I tried to make get_sample for SineWave accept *Self but zig complains about unused parameter...