jinzhu / copier

Copier for golang, copy value from struct to struct and more
MIT License
5.57k stars 489 forks source link

Inconsistent Field Copying Behavior with Different Field Types #207

Open knbr13 opened 9 months ago

knbr13 commented 9 months ago

Reproducible Example

package main

import (
    "fmt"

    "github.com/jinzhu/copier"
)

func main() {
    i := 130
    j := int8(32)
    err := copier.Copy(&j, i)
    if err != nil {
        panic(err)
    }
    fmt.Printf("j: %d\n", j) // output: -126 // (bit overflow)
}

Note: the provided example is just to highlight the problem, but it's not the good example for it, I'll provide more convenient example (and more likely to happen) at the bottom of this issue description.

Description

When copying from source of type int to destination of type int but smaller size like int8, the result is not as expected. The value of source is set to destination but because of the limited size of the destination, the value of source may overlap (if larger than the maximum size of destination), so that the value of destination become unexpected.

package main

import (
    "fmt"

    "github.com/jinzhu/copier"
)

type Exam struct {
    Name         string
    Date         string
    Subject      string
    School       string
    NbOfStudents int8
}

func main() {
    data := struct {
        Name         string
        Date         string
        Subject      string
        School       string
        NbOfStudents int
    }{
        Name:         "<NAME>",
        Date:         "2020-01-01",
        Subject:      "Maths",
        School:       "University of Lille",
        NbOfStudents: 1250,
    }
    var e Exam
    err := copier.Copy(&e, data)
    if err != nil {
        panic(err)
    }
    fmt.Printf("exam: %+v\n", e)
    fmt.Printf("nb of students: %d\n", e.NbOfStudents) // output: -30
}