Copy one struct to another where structs have same members and different types

convert one struct to another golang
golang deep copy struct
golang deep copy string
golang clone struct pointer
golang struct
golang protobuf deep copy
golang deepcopy map
golang struct default value

I have two struct having the same members, I want to copy one struct to another, see the pseudo code below:

type Common struct {
    Gender int
    From   string
    To     string
}

type Foo struct {
    Id    string
    Name  string
    Extra Common
}

type Bar struct {
    Id    string
    Name  string
    Extra Common
}

Then I have foo of struct Foo, and bar of struct Bar, Is there any way to copy bar from foo?

Use a conversion to change the type. The following code uses a conversion to copy a value of type Foo to a value of type Bar:

foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)

playground example

The conversion only works when the underlying types are identical except for struct tags.

Go- Copy all common fields between structs, You have to further develop it if you need more complex structures with embedded struct fields and such. http://play.golang.org/p/iTaDgsdSaI package main import ( "encoding/json" "fmt" "reflect" ) type M You can cast structures if they have same field names and types, Cancel and add another image. If you would like to copy or clone to a different struct, I would suggest using deepcopier It provides nice features like skipping, custom mapping, and forcing. You can achieve nested struct copy following way.

If you would like to copy or clone to a different struct, I would suggest using deepcopier

It provides nice features like skipping, custom mapping, and forcing. below is an example from github:

Install:

go get -u github.com/ulule/deepcopier

Example:

package main

import (
    "fmt"

    "github.com/ulule/deepcopier"
)

// Model
type User struct {
    // Basic string field
    Name  string
    // Deepcopier supports https://golang.org/pkg/database/sql/driver/#Valuer
    Email sql.NullString
}

func (u *User) MethodThatTakesContext(ctx map[string]interface{}) string {
    // do whatever you want
    return "hello from this method"
}

// Resource
type UserResource struct {
    //copy from field "Name"
    DisplayName            string `deepcopier:"field:Name"`
    //this will be skipped in copy 
    SkipMe                 string `deepcopier:"skip"`
    //this should call method named MethodThatTakesContext 
    MethodThatTakesContext string `deepcopier:"context"`
    Email                  string `deepcopier:"force"`

}

func main() {
    user := &User{
        Name: "gilles",
        Email: sql.NullString{
            Valid: true,
            String: "gilles@example.com",
        },
    }

    resource := &UserResource{}

    deepcopier.Copy(user).To(resource)
    //copied from User's Name field
    fmt.Println(resource.DisplayName)//output: gilles
    fmt.Println(resource.Email) //output: gilles@example.com
    fmt.Println(resource.MethodThatTakesContext) //output: hello from this method
}

Also, some other way you could achieve this is by encoding the source object to JSON and then decode it back to the destination object.

Making a copy of a struct in Go, A struct variable in Go can be copied to another variable very easily using Println("Roger and mydog are equal structs") } } play mydog and roger the other object, because the Dog struct contains basic types, which are copied by value. https://github.com/jinzhu/copier is (one of the many) deep copy  I don't consider that good advice, since mem functions should generally be avoided in C++. In fact, it will fail when one of the struct members is a compound C++ type that normally requires a call to a (copy-) constructor to be initialized corectly - one obvious example would be std::string.

https://github.com/jinzhu/copier (same author of gorm) is also quite a good one, I have nested structs and all I do is:

copier.Copy(&employees, &user)

works great

Professional C#, The following snippet shows how to copy values from one struct to another: EmployeeInfo employee1; EmployeeInfo The struct members cannot have initializers. Structs. and. attributes. Attributes (or compiler directives, discussed in Chapter 10 It can be used to store values of different types in the same memory block. Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members. Or is it too much and it is better to have just one struct with first and second as members. What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

This is another possible answer

type Common struct { Gender int From string To string }

type Foo struct {
    Id    string
    Name  string
    Extra Common
}

type Bar struct {
    Id    string
    Name  string
    Extra Common
}
foo:=Foo{
    Id:"123",
    Name:"damitha",
    Extra: struct {
        Gender int
        From   string
        To     string
    }{Gender:1 , From:"xx", To:"yy" },
}
bar:=*(*Bar)(unsafe.Pointer(&foo))
fmt.Printf("%+v\n",bar)

Shallow copy of a go struct in golang is never a good idea, Before we start with example, let's have a quick detour to… push to write this blogpost to prevent other people from having the same experience. variable with a struct to another variable makes a copy of that struct. One of the key takeways here is that structs evolve over time. String Data Type in Go. I want to copy an identical struct into another and later on use it as a comparance to the first one. The thing is that my compiler gives me a warning when Im doing like this! Should I do it in another way or am I doing this wrong:

If you would like to copy or clone to a different struct, I would suggest using deepcopier

It provides nice features like skipping, custom mapping, and forcing.

You can achieve nested struct copy following way. Install:

go get -u github.com/ulule/deepcopier

Example:

 package main

    import (
        "fmt"
        "strconv"

        "github.com/ulule/deepcopier"
    )

    //FieldStruct -  Field Struct
    type FieldStruct struct {
        Name string `deepcopier:"field:TargetName"`
        Type string `deepcopier:"field:TargetType"`
    }

    //SourceStruct - Source Struct
    type SourceStruct struct {
        Name        string   `deepcopier:"field:TargetName"`
        Age         int      `deepcopier:"field:TargetAge"`
        StringArray []string `deepcopier:"field:TargetStringArray"`
        StringToInt string   `deepcopier:"context"`
        Field       FieldStruct
        Fields      []FieldStruct
    }

    //TargetFieldStruct -  Field Struct
    type TargetFieldStruct struct {
        TargetName string
        TargetType string
    }

    //TargetStruct - Target Struct
    type TargetStruct struct {
        TargetName        string
        TargetAge         int
        TargetStringArray []string
        TargetInt         int
        TargetField       TargetFieldStruct
        TargetFields      []TargetFieldStruct
    }

    //write methods

    //TargetInt - StringToInt
    func (s *SourceStruct) TargetInt() int {
        i, _ := strconv.Atoi(s.StringToInt)
        return i
    }

    func main() {
        s := &SourceStruct{
            Name:        "Name",
            Age:         12,
            StringArray: []string{"1", "2"},
            StringToInt: "123",
            Field: FieldStruct{
                Name: "Field",
                Type: "String",
            },
            Fields: []FieldStruct{
                FieldStruct{
                    Name: "Field1",
                    Type: "String1",
                },
                FieldStruct{
                    Name: "Field2",
                    Type: "String2",
                },
            },
        }

        t := &TargetStruct{}

        //coping data into inner struct
        deepcopier.Copy(&t.TargetField).From(&s.Field)

        // copied array of Struct
        for i := range s.Fields {
            // init a struct
            t.TargetFields = append(t.TargetFields, TargetFieldStruct{})
            // coping the data
            deepcopier.Copy(&t.TargetFields[i]).From(&s.Fields[i])
        }
        //Top level copy
        deepcopier.Copy(t).From(s)

        fmt.Println(t)
    }

Output: &{Name 12 [1 2] 123 {Field String} [{Field1 String1} {Field2 String2}]}

copying structs with unexported fields, containing unexported fields to be assigned by other packages. use the copy and append builtins (6g does not get this right). say, copy an opaque unique id field from one structure to another. type someType struct { also not copyable for the same reason; fields, even though it does contain unexported members. How to copy field contents of one struct to another? Follow 488 views (last 30 days) I have got two structs, A and B. B has a subset of the fields of A:

Create a copy of a struct c, When you copy a class , C# creates a new copy of the reference to the object and A structure is a compound data type that contains different members of There are several different ways to define a struct type but weSo struct one and By the way, I am pretty sure I could do the same thing using an array of structs too. BTE320 Chapter 9. STUDY. to copy the contents of one struct into another struct of the same type. in a struct variable must be read one member at a time.

Copy Struct Type in Go Programming Language, Copy Struct Type Using Value and Pointer Reference As both r1 and r3 both reference the same underlying memory, their values are the same. is no store, so a worker who finished its part first must wait for others before starting another one. Structs are the only way to create concrete user-defined types in Golang. You can use an assignment statement to copy the contents of one struct into another struct of the same type.

Struct in Golang, declaring and creating Struct Data Type , Structs are the only way to create concrete user-defined types in Golang. A struct type rectangle is declared that has three data fields of different data-types. Nesting one struct within another can be a useful way to model more complex structures. r2 will be the same as r1, it is a copy of r1 rather than a reference to it. In a readonly struct, every instance member is implicitly readonly. Within a readonly instance member, you can't assign to structure's instance fields. However, a readonly member can call a non-readonly member. In that case the compiler creates a copy of the structure instance and calls the non-readonly member on that copy. As a result, the

Comments
  • Your intention isn't clear. What are you trying to do?
  • Cool. Apparently this only works if both structs have exactly the same structure..
  • ..but it doesn't work to make a copy to the same structure type
  • @CeriseLimón to copy a struct to another instance, the conversion doesn't actually do anything, while just assigning the value does it correctly.
  • @JohnWhite The question asks about different types, and that's what I answer here. A conversion is not required when there's no change in type. The code in the answer does work when the types are the same. Conversion to the same type does yield a new value of the type. That's not useful, but it does do something.