Función reflect.Copy() en Golang con ejemplos

El lenguaje Go proporciona una implementación de soporte incorporada de la reflexión en tiempo de ejecución y permite que un programa manipule objetos con tipos arbitrarios con la ayuda del paquete de reflexión. La función reflect.Copy() en Golang se usa para copiar el contenido de la fuente en el destino hasta que se complete el destino o se agote la fuente. Para acceder a esta función, es necesario importar el paquete reflect en el programa.

Sintaxis:

func Copy(dst, src Value) int

Parámetros: Esta función toma dos parámetros de tipo Slice o Array. Y dst y src deben tener el mismo tipo de elemento.

Valor devuelto: esta función devuelve el número de elementos copiados.

Los siguientes ejemplos ilustran el uso del método anterior en Golang:

Ejemplo 1:

// Golang program to illustrate
// reflect.Copy() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    // Source 
    src := reflect.ValueOf([]int{10, 20, 32})
      
    /* make sure the dest space is larger than src */
    // destination 
    dest := reflect.ValueOf([]int{1, 2, 3})
      
    // To copy Copy() function is used
    // and it returns the number of 
    // elements copied
    cnt := reflect.Copy(dest, src)
    data := dest.Interface().([]int)
    data[0] = 100
      
    // printing the values
    fmt.Println("Number of element Copied :", cnt)
    fmt.Println("Source :", src)
    fmt.Println("destination :", dest)
}

Producción:

Number of element Copied : 3
Source : [10 20 32]
destination : [100 20 32]

Ejemplo 2:

// Golang program to illustrate
// reflect.Copy() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Struct with two int value
type temp struct {
    A0 []int
    A1 []int
}
  
// Main function 
func main() {
      
    var val temp
      
    // Source 
    val.A0 = append(val.A0, []int{1, 2, 3,
                    4, 5, 6, 7, 8, 9}...)
      
    // destination 
    val.A1 = append(val.A1, 9, 8, 7, 6)
      
    // To copy Copy() function is used
    // and it returns the number of 
    // elements copied
    var n = reflect.Copy(reflect.ValueOf(val.A0), 
                        reflect.ValueOf(val.A1))
      
    // printing the values
    fmt.Println("Number of element Copied :", n)
    fmt.Println("{Source, destination} :", val)
      
}

Producción:

Number of element Copied : 4
{Source, destination} : {[9 8 7 6 5 6 7 8 9] [9 8 7 6]}

Publicación traducida automáticamente

Artículo escrito por SHUBHAMSINGH10 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *