-1

I have a package called server that contains a Settings struct. It contains code like this:

type Settings struct {
    foobar String
}

func example() {
    readSettings := Settings{}
    err := storage.GetSettings(&readSettings)
    // Problem: at this point, readSettings has not been changed!
}

My problem is that readSettings is not being updated.

In the storage package, there is a function GetSettings:

func GetSettings(settingsToPopulate interface{}) error {
    file, _ := os.Open("/tmp/settings.json")
    var decodedSettings interface{}
    json.NewDecoder(file).Decode(&decodedSettings)
    settingsToPopulate = decodedSettings
    return nil
}

My constraints are that the Settings struct must remain in server, and the IO method GetSettings much remain in storage.

I can't make GetSettings just accept a Settings struct, because that would cause a circular dependency.

How can I make the reference parameter of GetSettings be updated?

dylhunn
  • 989
  • 2
  • 8
  • 25
  • You could not passing anything at all and make `GetSettings` return all the values for `Settings` individually. Or you could use a map[string]interface{} as the return value, then convert it to a `Settings`. – hewiefreeman Apr 17 '19 at 23:41
  • 1
    `json.NewDecoder(file).Decode(settingsToPopulate)` ? – zerkms Apr 18 '19 at 00:53
  • Possible duplicate of [json.Marshal(struct) returns "{}"](https://stackoverflow.com/questions/26327391/json-marshalstruct-returns) – Peter Apr 18 '19 at 05:49
  • 1
    Export the fields. Also, don't forget to Close() the file when you're done with it. – Peter Apr 18 '19 at 05:50

1 Answers1

4

Here you don't need to use the intermediate variable decodedSettings. Instead, using the readSettings pointer you pass in directly will cause the JSON package to deserialise to that instead.

Your code will become:

func GetSettings(settingsToPopulate interface{}) error {
    file, _ := os.Open("/tmp/settings.json")
    return json.NewDecoder(file).Decode(settingsToPopulate)
}
Ewan
  • 14,592
  • 6
  • 48
  • 62