Skip to content

Inconsistent Field Copying Behavior with Different Field Types #207

@knbr13

Description

@knbr13

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
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions