How to use Golang reflection values to define a variable

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

Before writing Java has already known the concept of reflection, read the article specifically introduced the Java reflection mechanism, but now forget.

Today, when writing a general function to judge the incoming parameters by the row type, but also to define the same type of variables as the row fetch operation, Baidu, Google,golang reflect package also looked for a long time, also did not see the return value to define a variable method. Finally get inspired in a blog post-–> click to see.

This article does not tell how to define a variable, but after reading it to think about, since to return a type, but the type is indeterminate, if there is a function to return the variable, then its return type must be interface, In the official website The return type is a function of interface, that is, it is a function of the value type, so you cannot use reflect. TypeOf (i interface{}) to operate, you can only use reflect. ValueOf (). So slowly combined with the appeal blog plus documentation, get~

package mainimport (    "reflect"    "fmt")func main() {    "tangs"    fmt.Println("v2's value is : "", type is : ", reflect.TypeOf(v2))    ty := reflect.ValueOf(&v2).Elem()    s := ty.Interface()    "tangs"    fmt.Println("s's value is : "", type is : " ,reflect.TypeOf(s))}

Result:

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.