Hello,
I am trying to figure out how to initialize a static array of struct elements using the literal syntax. I didn’t find examples of this in the language reference, so I wonder if what I am trying even makes sense, or maybe isn’t recommended or something.
Anyway, there is clearly something I am missing, can you help?
Here is what my code looks like:
const std = @import("std");
const NoteEvent = struct {
pitch: u8,
velocity: u8,
note_position: f32,
duration: f32,
pub fn debugPrint(self: @This()) void {
std.debug.print("NoteEvent{{ .pitch = {[pitch]}, .velocity: {[velocity]}, .note_position: {[note_position]}, .duration: {[duration]} }}\n", self);
}
};
fn printNotes(notes: []NoteEvent) void {
for (notes) |note| {
note.debugPrint();
}
}
pub fn main() !void {
// this was my first naive attempt, with this I get an error:
// error: type '[]main.NoteEvent' does not support array initialization syntax
const notes: []NoteEvent = []NoteEvent{
NoteEvent{ .pitch = 60, .velocity = 127, .note_position = 0, .duration = 1 },
NoteEvent{ .pitch = 62, .velocity = 127, .note_position = 1, .duration = 3 },
};
printNotes(notes);
}
After the above attempt, I searched on the internet and realized I probably needed to create an array, so tried the following things:
1:
// make an array, with an inferred size. I get this error:
// error: array literal requires address-of operator (&) to coerce to slice type '[]main.NoteEvent'
const notes: []NoteEvent = [_]NoteEvent{
NoteEvent{ .pitch = 60, .velocity = 127, .note_position = 0, .duration = 1 },
NoteEvent{ .pitch = 62, .velocity = 127, .note_position = 1, .duration = 3 },
};
2:
// then I add the & operator, I get:
// error: unable to infer array size
const notes: []NoteEvent = [_]NoteEvent&.{
NoteEvent{ .pitch = 60, .velocity = 127, .note_position = 0, .duration = 1 },
NoteEvent{ .pitch = 62, .velocity = 127, .note_position = 1, .duration = 3 },
};
3:
// so I try to add the size manually, and then I get:
// error: incompatible types: 'type' and 'struct{comptime main.NoteEvent = .{ .pitch = 60, .velocity = 127, .note_position = 0, .duration = 1 }, comptime main.NoteEvent = .{ .pitch = 62, .velocity = 127, .note_position = 1, .duration = 3 }}'
const notes: []NoteEvent = [2]NoteEvent & .{
NoteEvent{ .pitch = 60, .velocity = 127, .note_position = 0, .duration = 1 },
NoteEvent{ .pitch = 62, .velocity = 127, .note_position = 1, .duration = 3 },
};
- ask for help: this post
So, what am I missing?
Thanks!