Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

go - Unmarshaling Into an Interface{} and Then Performing Type Assertion

I get a string through a rabbitmq message system. Before sending,

I use json.Marshal, convert the outcome to string and send through rabbitmq.

The structs that I convert and send can be: (changed the names and the size of the structs but it should not matter)

type Somthing1 struct{
   Thing        string    `json:"thing"`
   OtherThing   int64     `json:"other_thing"`
}

or

type Somthing2 struct{
   Croc        int       `json:"croc"`
   Odile       bool      `json:"odile"`
}

The message goes through perfectly as a string and is printed on the other side (some server)

Up until now everything works. Now I'm trying to convert them back into their structs and assert the types.

first attempt is by:

func typeAssert(msg string) {

 var input interface{}

 json.Unmarshal([]byte(msg), &input)

 switch input.(type){
 case Somthing1:
    job := Somthing1{}
    job = input.(Somthing1)
    queueResults(job)

  case Somthing2:
    stats := Somthing2{}
    stats = input.(Somthing2)
    queueStatsRes(stats)
 default:
}

This does not work. When Printing the type of input after Unmarshaling it I get map[string]interface{} (?!?)

and even stranger than that, the map key is the string I got and the map value is empty.

I did some other attempts like:

 func typeAssert(msg string) {

  var input interface{}

  json.Unmarshal([]byte(msg), &input)

  switch v := input.(type){
  case Somthing1:
    v = input.(Somthing1)
    queueResults(v)

   case Somthing2:
    v = input.(Somthing2)
    queueStatsRes(v)
  default:
}

and also tried writing the switch like was explained in this answer: Golang: cannot type switch on non-interface value

switch v := interface{}(input).(type)

still with no success...

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...