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

Incorrect nil copy #2

Open
alresvor opened this issue Nov 15, 2022 · 4 comments
Open

Incorrect nil copy #2

alresvor opened this issue Nov 15, 2022 · 4 comments
Labels
bug Something isn't working NeedsInvestigation

Comments

@alresvor
Copy link

alresvor commented Nov 15, 2022

https://go.dev/play/p/DwZgPX8HhBs

package main

import (
	"fmt"

	"golang.design/x/reflect"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func main() {
	n := ListNode{Val: 1}
	n2 := reflect.DeepCopy(n)
	fmt.Printf("%+v %+v\n", n, n2)
	fmt.Println(n2.Next.Val) // 0
}

n.Next is nil, but becomes &ListNode{} after the deep copy.

@changkun
Copy link
Member

Interesting, perhaps the recursive processing was not correct engouth.

@alresvor
Copy link
Author

最简单的:

	var n4 *ListNode
	n5 := reflect.DeepCopy(n4)
	fmt.Println(n4, n5) // <nil> &{0 <nil>}

@alresvor
Copy link
Author

alresvor commented Nov 15, 2022

这里还有一个 deepCopy 的库,倒是没有这个问题,而且实现简单粗暴
https://github.com/darkgopher/darkness/blob/master/deepcopy.go

@changkun changkun added the bug Something isn't working label Nov 16, 2022
@changkun
Copy link
Member

I don't yet have time to look deeper into this. Hence it is greatly welcome if there is a PR to fix this

@changkun changkun changed the title 复制了错误的 nil 值 Incorrect nil copy Nov 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working NeedsInvestigation
Projects
None yet
Development

No branches or pull requests

2 participants