Last active
March 29, 2023 09:32
-
-
Save penglongli/a0698546f1026731c81c0d327a3d6b32 to your computer and use it in GitHub Desktop.
golang deep-copy interface with reflect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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