0

For a test, with an unmarshalling function I received a unit variable, having a struct Unit for structure:

type Unit struct {
    ID           string            `json:"ID"`
    Name         *string           `json:"name"`
    CategoryCode *UnitCategoryCode `json:"categoryCode"`
    ... // and a lot of others
}

It is valued that way: {ID: something, Name: something, CategoryCode: nil}. It's the test case.

To continue my test, I would like to assign something to CategoryCode. A value that CategoryCode knows (under a d named import) as AdministrativeUnit

If I do a:

*unit.CategoryCode = d.AdministrativeUnit

It compiles, but do a nil panic, because of course unit.CategoryCode is nil:
*(unit.CategoryCode) has no sense.

but:

unit.CategoryCode = d.AdministrativeUnit

doesn't compile. type (UnitCategoryCode) against (*UnitCategoryCode)

unit->CategoryCode = &d.AdministrativeUnit

doesn't exist

and

unit.CategoryCode = &d.AdministrativeUnit

doesn't want to take the address of d.AdministrativeUnit that is a const.

I surely need to use a new somewhere, here. But how?

Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
  • 1
    You can't take the address of a constant (because they don't have one). You'll need to either store `CategoryCode` by value or declare `AdministrativeUnit` as a `var`. – isaactfa Jun 29 '23 at 11:03
  • Or assign `AdminstrativeUnit` to a variable and then assign the pointer to that variable to `unit.CategoryCode`. – isaactfa Jun 29 '23 at 11:05
  • 1
    Simplest is to use a reusable `func Ptr[T any](v T) *T { return &v }` helper function to obtain a pointer to any value. This should be a builtin function... – icza Jun 29 '23 at 12:15

0 Answers0