mercredi 26 octobre 2022

How to judge the type of Struct and modify it in Golang?

Original question:

I want to make a function that takes in different commodity Struct and encrypts their ids. I have a encryption function:

func encryption(in string, typeOf string) string {
  result := in + typeOf
  return result } 

and 2 commodity Struct:

type cloth struct {
  clothId   string
  name string }

type pants struct {
  pantsId   string
  name string } 

I want to modify them through a function, by passing in variadic parameters, to perform different operations, it should modify the id of the Struct

func encryptId(in interface{}) {
  switch in := in.(type) {
  case cloth:
      in.clothId = encryption(in.clothId, "cloth")
  case pants:
      in.pantsId = encryption(in.pantsId, "pants")
  default:
      return
  }
}

But although this function can determine the type, it cannot modify them, how can I do? I found theseonline, but it can only judge and not modify. I hope after doing this

func main() {
  clo := cloth{"cloth", "blue"}
  pan := pants{"pants", "green"}
  encryptId(clo)
  encryptId(pan)
  fmt.Println(clo)
  fmt.Println(pan) }

it will output

{clothcloth blue}

{pantspants green}

Solved by mkopriva

It cannot modify them because they are copies. Use pointers instead. E.g. encryptId(&clo) and inside the function's switch use case *cloth:

go.dev/play/p/4uYzqZ0BKVy (note the assignment in the switch statement, i.e. switch in := in.(type) {)

func encryptId(in interface{}) {
    switch in := in.(type) {
    case *cloth:
        in.id = encryption(in.id)
    case *pants:
        in.id = encryption(in.id)
    default:
        return
    }
}

func main() {
    clo := cloth{"cloth", "blue"}
    pan := pants{"pants", "green"}
    encryptId(&clo)
    encryptId(&pan)
    fmt.Println(clo)
    fmt.Println(pan)
}

Done.





Aucun commentaire:

Enregistrer un commentaire