Go language reflection mechanism

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

The reflection mechanism is basically similar to Java, which can get information such as the type value of a struct or variable. When you get or modify the value of an object, be sure to determine whether the property is operational or it will cause an error.

The sample code is as follows:

Package Mainimport ("FMT" "reflect")///initial uppercase indicates that the field can be exported and can modify the value type User struct {ID   intname string//not exported age  int} Func (U User) Info () {fmt. Println (U)}func GetInfo (o interface{}) {t: = reflect. TypeOf (o) fmt. Println (T.name ()) V: = reflect. ValueOf (o) for I: = 0; I < T.numfield (); i++ {f: = T.field (i) fmt. Printf ("%s\n", F.name) if V.field (i). Caninterface () {///Here name is not exported, so when getting interface it will prompt for error val: = V.field (i). Interface () fmt. Printf ("%s:%v=%v\n", F.name, F.type, Val)}}}func main () {user1: = user{222, "Charles", 100}getinfo (User1)}


Related Article

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.