Copying Golang Structs

Golang (or Go language) is renowned for its efficiency and high performance. Among its strengths, structs are powerful tools for representing data. However, copying Golang structs can sometimes be confusing. In this article, we will introduce three or more basic methods for copying structs and provide clear explanations with code examples.

Methods for Copying Structs

Method 1: Simple Assignment

The most straightforward method is to use simple assignment. This method is applicable when the original struct and the target struct for copying have the same type.

package main

import "fmt"

type Person struct {
    FirstName string
    LastName  string
}

func main() {
    person1 := Person{"John", "Doe"}
    var person2 Person

    person2 = person1 // Struct copying

    fmt.Println(person2)
}

Method 2: Copying Using Pointers

You can also copy structs using pointers. This allows the original struct and the target struct to share the same memory.

package main

import "fmt"

type Person struct {
    FirstName string
    LastName  string
}

func main() {
    person1 := &Person{"John", "Doe"}
    var person2 *Person

    person2 = person1 // Copying using pointers

    fmt.Println(*person2)
}

Method 3: Copying Using the copy() Function

You can also copy structs using the copy() function. This method is useful when structs are within a slice, among other situations.

package main

import "fmt"

type Person struct {
    FirstName string
    LastName  string
}

func main() {
    person1 := Person{"John", "Doe"}
    personSlice := []Person{person1}
    var person2 Person

    copy(personSlice, personSlice) // Copying using the `copy()` function

    person2 = personSlice[0]

    fmt.Println(person2)
}

By using these methods, you can understand the basic ways to copy structs in Golang. Choose the appropriate method depending on your specific situation. Regardless of the method chosen, copying structs in Golang is a simple and efficient operation.

タイトルとURLをコピーしました