#Accessing fields in struct

1 messages · Page 1 of 1 (latest)

random hemlock
#

I want to extract the contents of each field in BrickColors and place the contents into an array, doing so gives me the error

gusty kestrel
#

fields need the instance as the first argument to @field, not the type which only works for decls

random hemlock
#

so ray.Color?

gusty kestrel
#

that's also a type

random hemlock
#

so i assume the brick_color which is the in argument

gusty kestrel
#

that looks good

#

you also probably need to do var colors: [fields.len]ray.Color = undefined;

abstract ridge
# random hemlock

This is illegal behavior btw
colors[i] accesses colors.ptr which is undefined

random hemlock
prisma delta
#

remove the inline

gusty kestrel
#

no you definitely need inline, see my last message

random hemlock
prisma delta
#

nvm im blind 😄

random hemlock
#

np

prisma delta
#

i didnt see you make the colors comptime

gusty kestrel
#

You need inline because fields is comptime-only, but you need (non-comptime) var because brick_color is runtime

abstract ridge
#

Wouldn't you want

var colors: [brick_color_count]ray.Color = undefined
random hemlock
#

well the latest is

src/main.zig:79:15: error: cannot store runtime value in compile time variable
        colors[i] = @field(brick_color, field.name);?

with

const fields = @typeInfo(BrickColors).Struct.fields;
    const brick_color_count = fields.len;

    comptime var colors: [brick_color_count]ray.Color = undefined;
    inline for (fields, 0..) |field, i| {
        colors[i] = @field(brick_color, field.name);
    }
random hemlock
#

but it crashed pretty much instantly

abstract ridge
#

It'll compile but it'll probably segfault on runtime

#

Yeah

prisma delta
#

you need an allocator and do:

var colors = allocator.alloc(ray.Color, brick_color_count)
abstract ridge
#

brick_color_count is known at compile time

#

You can just use an array

prisma delta
#

oh yeah 🤣

abstract ridge
#

If you're returning colors you would need to allocate it though
Unless you want to return it by value

random hemlock
#

so it might be another issue that's unrelated to this

#

so thankks for the help, i'm closer now

#

it works!

#

just need some more colors so the effort was worth it