go-reflection mechanism

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

Ideas

Structure objects mapped out: Class name, member name, member value



Package Daoimport (_ "Chbeegotest/models" "Chbeegotest/utils/mylog" "FMT" "Reflect" "strings") type Dao struct {}var Daointer = new (Dao)//Maps the object to a table, returns the primary key Idfunc (this *dao) Insert (obj interface{}) {//object to table tables: = obj2table (obj) fmt. Println (table. Tbname)//Serialization of column name cloums: = Strings. Join (table. Cloum, ",") fmt. PRINTLN (cloums)//INSERT statement stmt, err: = Db.prepare (' Insert User (username,password,truename,mail,headimg,lastlogin,coin) VALUES (?,?,?,?,?,?,?) ' If err! = Nil {myLog.Logger.Fatal (err)}res, err: = stmt. Exec (Table.values ...) If err! = Nil {fmt. Print ("Insert Failed") MyLog.Logger.Fatal (Err)}id, err: = Res. Lastinsertid () fmt. Print ("Insert succeeded, insert ID:", id)}type table struct {tbname string//fild Map[string]interface{}cloum []stringvalues []INTERFAC] E{}}type User struct {playerid intusername stringpassword stringtruename stringmail stringheadimg stringLastLog In Uint64coin int}//object is converted to table func obj2table (obj interface{}) *table {tb: = new (table) Typeobj: = reflect. TypeOf (obj)//table name TB. Tbname = Typeobj.elem (). Name ()//column//TB. Fild = Make (map[string]interface{}) TB. Cloum = Make ([]string, 1) tb.values = "Make" ([]interface{}, 1) for I: = 0; I < Typeobj.elem (). Numfield (); i++ {//Column name Cloumname: = Typeobj.elem (). Field (i). Nametb.cloum = Append (tb. Cloum, Cloumname)//Column value val: = Reflect. ValueOf (obj). Elem (). Fieldbyname (cloumname) tb.values = Append (Tb.values, Val)//Loading MAP//TB. Fild[cloumname] = Val}return TB}


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.