On Saturday, August 24, 2019 at 3:39:27 AM UTC-4, Lee Rick wrote:
>
> think that there are two struct, they have different fields, hope that 
> there has a function merge(a,b interface{}) interface{}, input param are 
> any two struct, they may have same-type, or have different-type. output 
> param is a struct that composed the two input struct, example type A 
> sturct{Name string}, type B struct{Age int}, a,b :=A{"xxx"},B{10} called 
> c:= merge(a,b), c is interface{}, and 
>
> import "github.com/google/go-querystring/query",
>
> v, _ := query.Values(opt)
> fmt.Print(v.Encode()) // will output: "name=xxx&age=10"
>
>
>
This still sounds very much like the XY Problem <http://xyproblem.info/>. 
If you goal is really to combine two structs for the purpose of encoding 
them using the net/url Value type, then the using reflection to create a 
new type is probably overly complicated and inefficient. A much simpler, 
and more idiomatic, way to achieve the same result would be to merege the 
url.Value's created from two calls to query.Values(). Something like:
package main

import "fmt"
import "github.com/google/go-querystring/query"

type A struct{ Name string }
type B struct{ Age int }

func main() {
    a := A{Name: "foo"}
    b := B{Age: 7}

    va, _ := query.Values(a)
    vb, _ := query.Values(b)

    for k, vslice := range vb {
        fmt.Println("Key: ", k, "Value: ", vslice)
        for _, v := range vslice {
            va.Add(k, v)
        }
    }
    fmt.Print(va.Encode())
}
This is just an example, and the combining logic could be pulled out into a 
general function. 

If on the other hand, you have a situation where you are passing an 
interface{} to code *over which you have no control*, then reflection *may *be 
the best way. However, you should probably refernce the specific code (over 
which you have no control) so others could help find a possible solution 
based on you actual problem. 

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/6d1b0d03-4c20-4fe0-a307-7ce7487d61fc%40googlegroups.com.

Reply via email to