Skip to content

Instantly share code, notes, and snippets.

@penglongli
Last active March 29, 2023 09:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penglongli/a0698546f1026731c81c0d327a3d6b32 to your computer and use it in GitHub Desktop.
Save penglongli/a0698546f1026731c81c0d327a3d6b32 to your computer and use it in GitHub Desktop.
golang deep-copy interface with reflect
package main
import (
"reflect"
"fmt"
)
type Cloneable interface {
Clone(inter interface{}) interface{}
}
type Element interface {
Cloneable
HashCode() int64
Value() int64
}
type Entity struct {}
func (e *Entity) Clone(inter interface{}) interface{} {
nInter := reflect.New(reflect.TypeOf(inter).Elem())
val := reflect.ValueOf(inter).Elem()
nVal := nInter.Elem()
for i := 0; i < val.NumField(); i++ {
nvField := nVal.Field(i)
nvField.Set(val.Field(i))
}
return nInter.Interface()
}
// Through HashCode function, to compare whether equals
// In this case, no implement it
func (e *Entity) HashCode() int64 { return 1 }
// Through HashCode function, to compare priority
// In this case, no implement it
func (e *Entity) Value() int64 { return 1 }
type Apple struct {
Entity
Weight int
Height int
}
func (apple *Apple) HashCode() int64 {return 1}
func (apple *Apple) Value() int64 {return 1}
func main() {
apple := &Apple{Weight:11, Height:14}
nApple := apple.Clone(apple).(*Apple)
apple.Weight = 1111
fmt.Println(apple)
fmt.Println(nApple)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment