Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent Field Copying Behavior with Different Field Types #207

Open
knbr13 opened this issue Feb 15, 2024 · 0 comments
Open

Inconsistent Field Copying Behavior with Different Field Types #207

knbr13 opened this issue Feb 15, 2024 · 0 comments
Assignees

Comments

@knbr13
Copy link

knbr13 commented Feb 15, 2024

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants