Skip to content

Instantly share code, notes, and snippets.

@andboson
Created January 23, 2021 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andboson/65737b99ff7ce804276e9ee77c457cde to your computer and use it in GitHub Desktop.
Save andboson/65737b99ff7ce804276e9ee77c457cde to your computer and use it in GitHub Desktop.
assign error by reflection
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