1

I have a structure, where I store all the hours and minutes into mongodb. In this case, when I get a request to modify the value, I get the hour and minute as string. Is there a way to find the field name from the string that is given as input

You can see it here

package main

import "fmt"

type Min struct {
    v01 int `bson:"01",json:"01"`
    v02 int `bson:"02",json:"02"`
}

type Hour struct {
    v01 Min `bson:"01",json:"01"`
    v02 Min `bson:"02",json:"02"`
}

func main() {
    fmt.Println("Hello, playground")
    var h Hour
    h.v01.v01 = 1
    h.v02.v01 = 2
    fmt.Println(h)
    h.Set("01", "01", 10)
    fmt.Println(h)
}

func (h *Hour) Set(hour string, min string, value int) {
    h.v01.v01 = 10 //Here I have hardcoded it
    // Is there a way to do this from the given input
    // e.g. h.Set("01","01",100)
}

If you notice, the input is "01","01". I would like to change this input as h.v01.v01. Is it possible in Go?

Note: I am using currently maps in this case. I would like to change this into structure access, if possible, so that I can use goroutine to speed up my program. Currently goroutines are not safe for writing into maps.

Sundar
  • 1,691
  • 1
  • 14
  • 20
  • 5
    Goroutines are not safe for concurrently writing *anything*. Regardless if you have a map or a struct, you need to synchronize access. – JimB Nov 05 '15 at 16:53
  • Possible duplicate of [GoLang: Access struct property by name](http://stackoverflow.com/questions/18930910/golang-access-struct-property-by-name) – Ainar-G Nov 05 '15 at 16:54

1 Answers1

0

Currently goroutines are not safe for writing into maps.

That might need to be revisited with Go 1.9 (Aug. 2017) and the concurrent map present in the sync package

The new Map type in the sync package is a concurrent map with amortized-constant-time loads, stores, and deletes.
It is safe for multiple goroutines to call a Map's methods concurrently.

Combine that with oleiade/reflections that I mentioned, as commented, in "GoLang: Access struct property by name", and you should be able to do both (access property name, and use maps)

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250