-
Notifications
You must be signed in to change notification settings - Fork 28
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
Suggestion: use the type's own Clone method #11
Comments
Might be better to use |
英文不行,中文说吧。 又发现目前
|
我理解你的意思是说,类似 SetCustomFunc(reflect.TypeOf(tls.Config{}), func(allocator *Allocator, old, new reflect.Value) {
// As tls.Config must be used as a pointer, it's quite unlikely to be unaddressable.
if !old.CanAddr() {
panic("tls.Config must be used as a pointer")
}
// Convert old to *tls.Config.
oldConfig := old.Addr().Interface().(*tls.Config)
// Call tls.Config's Clone() to create a copy of old.
newConfig := oldConfig.Clone()
// Copy the newly created cloned value to new.
// We don't need to worry about copying mutex inside tls.Config.
// It's safe to copy a zero mutex as it's just a zero value without any side effect.
new.Set(reflect.ValueOf(newConfig).Elem())
}) |
多谢回复,这个问题在2楼我已经意识到了,确实通过 现在比较关心的是例如有一个结构体里有巨多的字段,且部分字段的类型实现了
然后我想对这个结构体类型定义其自身的 那这个结构体类型的 所以希望能将
透出给 |
有一种 hack 的方法能够简单的实现,下面是样例代码。基本原理是,将 func ExampleSetCustomFunc_partialClone() {
type T1 struct {
Value int
}
type T2 struct {
Value int
}
type MyStruct struct {
S1 *T1
S2 *T2
S3 string
}
type MyStructAlias MyStruct
var typeOfMyStruct = reflect.TypeOf(MyStruct{})
var typeOfMyStructAlias = reflect.TypeOf(MyStructAlias{})
SetCustomFunc(reflect.TypeOf(T1{}), func(allocator *Allocator, old, new reflect.Value) {
oldField := old.FieldByName("Value")
newField := new.FieldByName("Value")
newField.SetInt(oldField.Int() + 100)
})
SetCustomFunc(reflect.TypeOf(T2{}), func(allocator *Allocator, old, new reflect.Value) {
oldField := old.FieldByName("Value")
newField := new.FieldByName("Value")
newField.SetInt(oldField.Int() + 100)
})
SetCustomFunc(reflect.TypeOf(MyStruct{}), func(allocator *Allocator, old, new reflect.Value) {
old = old.Convert(typeOfMyStructAlias)
new.Set(allocator.Clone(old).Convert(typeOfMyStruct))
field := new.FieldByName("S3")
field.SetString(field.String() + "_suffix")
})
st := &MyStruct{
S1: &T1{
Value: 1,
},
S2: &T2{
Value: 2,
},
S3: "abc",
}
cloned := Clone(st).(*MyStruct)
json, _ := json.Marshal(cloned)
fmt.Println(string(json))
// Output:
// {"S1":{"Value":101},"S2":{"Value":102},"S3":"abc_suffix"}
} |
提交了一个 PR #12,有了这个之后就能够在 |
简直太棒了,在这学习到一些东西。 👍👍 |
example:
*tls.Config Clone
method will do some thread-safe processing internallyThe text was updated successfully, but these errors were encountered: