Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Fluue
Jan 2, 2008
Trying to understand an idiomatic approach to a set-once lazy value for a struct.

I have a simple struct:

code:
type MyObject struct {
	ID              uint32 `db:"id"`
	Name            string `db:"name"`
	shiny           *bool
	types           []ObjectType
}

//
func (o *MyObject) IsShiny() bool {
	// TODO: implement randomness
	return o.shiny
}
I'm initializing and hydrating instances of MyObject from data I retrieve in a database and there are often multiple instances that I construct and return to the caller. The shiny field is determined by a random dice roll and is only set once for the lifetime of the struct.

Should I:
1. Pass in an instance of a seeded *rand.Rand() to IsShiny and only calculate it if o.shiny == nil
2. Create a constructor that accepts *rand.Rand() and do the dice roll during construction

My goal is to be able to test the IsSiny function and make sure the `shiny` field can't be changed after it's set.

edit: also, the dice roll does not need to be perfectly random

Fluue fucked around with this message at 03:56 on Sep 5, 2021

Adbot
ADBOT LOVES YOU

Fluue
Jan 2, 2008
Thank you both! Good suggestion to use an internal constructor.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply