#replacing container-level `var`

1 messages · Page 1 of 1 (latest)

sinful shore
#

container-level vars are bad, what should I use instead to accomplish, as closely as possible, the same thing?
example:

var instance: *SomeStruct = undefined;

pub fn init(alloc: std.mem.Allocator) !void {
  instance = try alloc.create(SomeStruct);
}
knotty pier
#

If what you want is a singleton, that's the default approach. If you want a non OOP approach, then it depends on what you want to do

sinful shore
#

I do wan singletons, but zls marks them (container-level vars) and I was curius if there was a "better" approach to singletons

knotty pier
#

Not really, the better approach is not using singletons

#

There is also std.once for only calling a function once

dull vector
#

is there any good reason to heap allocate the instance?

paper grove
#

It's OK to have just one of something and not make it a singleton.

sinful shore
#

this might be a better example

dull vector
#

but if you just use var instance: SomeStruct, you are still able to change its member later i think

sinful shore
#

you're right, i dont remember if there was any other reasons why i heap allocate - i just did it at the beginning and stuck with it

#

i just switched all those instances to not be pointers and everything works fine

sick solar
sinful shore
#

yeah but there are a lot of them

#

all of these have some "instance" inside of them (except driver.zig, which defines the interface all the rest use)

arctic grove
#

make a GameState struct that holds them all and pass pointers to that around :P

#

thats generally what i do

knotty pier
sinful shore
sinful shore
#

just refactored them all to use an "instances" struct inside the engine

#

works out pretty well and i functionally achieve the same thing