golang-using reflection to assign values to structures

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Because you want to assign a value to some members of a struct, but have no specific name, the JSON name of the tag is indexed and assigned by JSON name one by one

//assigning members in a struct to JSON namesFunc Setstructfieldbyjsonname (PTRInterface{}, Fields map[string]Interface{}) {logger. Debug ("Fields :", Fields) V:= Reflect. ValueOf (PTR). Elem ()//The struct variable     forI: =0; I < V.numfield (); i++{fieldInfo:= V.type (). Field (i)//a reflect. StructfieldTag: = Fieldinfo.tag//a reflect. StructtagName: = tag. Get ("JSON")        ifName = =""{Name=strings. ToLower (fieldinfo.name)}//remove the comma after the content such as ' JSON: ' Voucher_usage,omitempty 'Name = Strings. Split (Name,",")[0] Logger. Debug ("Jsonname:", name)ifValue, OK: =Fields[name]; OK {logger. Debug ("Fieldinfo.name:", Fieldinfo.name)//Assigning a value to a struct//Guaranteed data type consistency when assigning valuesLogger. Debug ("Type 1:", reflect. ValueOf (value). Type (),"Type 2:", V.fieldbyname (fieldinfo.name). Type ())ifReflect. ValueOf (value). Type () = =v.fieldbyname (fieldinfo.name). Type () {v.fieldbyname (fieldinfo.name). Set (reflect. ValueOf (value)) }}}return}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.