Created
January 23, 2021 14:55
-
-
Save andboson/65737b99ff7ce804276e9ee77c457cde to your computer and use it in GitHub Desktop.
assign error by reflection
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 ( | |
"errors" | |
"fmt" | |
"reflect" | |
) | |
type TestStruct struct { | |
E error | |
} | |
func some(trg interface{}) { | |
v := reflect.ValueOf(trg) | |
typeOfS := v.Elem().Type() | |
v2 := reflect.ValueOf(errors.New("new error")) | |
v.Elem().Field(0).Set(v2.Convert(typeOfS.Field(0).Type)) | |
} | |
func main() { | |
s := TestStruct{} | |
some(&s) | |
fmt.Printf("%+v", s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment