Golang Type Assertion

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

Golang interface type is a great artifact of Golang, let's look at how to convert the interface type to other types

Packagetests

Import(
  "FMT"
  "Github.com/go-xorm/core"
  "Github.com/go-xorm/xorm"
  _"Github.com/lunny/godbc"
  "OS"
  "Testing"
  "Zks.com/business/module"
)
varDBE*xorm. Engine
Functest_initdb (t*testing. T){
  dbhost:="localhost\MSSQLSERVER2008" 
  dbname: ="FOODSAFETY_KF"
  dbuser: ="sa"
  dbpwd: ="Sasa"
  varErr error 
    DBE, Err = Xorm.Newengine("ODBC", Fmt.Sprintf("Driver=sql server;server=%s;d atabase=%s; uid=%s; pwd=%s;",
  dbhost,dbname,dbuser,dbpwd)) 
&NBSP;&NBSP;&NBSP;&NBSP;  if    err< Span style= "COLOR: #ff00dc" >  !=    nil    {  
  fmt. Println("failedtoinitializeDatabase" )
  os. Exit(2) 
    }
  DBE. Setmapper(core. Samemapper{}) 
  DBE. showdebug=true
  DBE. showerr=true
  DBE. showsql=true
}
Functest_something (t*testing. T){
  list:=new([]module. Base_module) 
  getdata(list) 
}
Funcgetdata (datainterface{}){
&NBSP;&NBSP;&NBSP;&NBSP;  dbe.  Limit ( 3   Find ( data  
  ifm,OK:=data. ( *[]module. Base_module); Ok{  
  D:=*m
          for    i  :=    0  ;    i  <    len   ( D    i++    Span style= "COLOR: #bbbbbb" >{  
  fmt. Println(d[i]. Fullname) 
        }
    }
}
In the above code, I new a struct array, and then send a pointer to the struct array as a parameter to the GetData function, and GetData this function to receive this parameter with interface{} to receive, So the pointer is converted into an interface type.

If we remove M,OK : =data. ( *[]module. Base_module) This sentence, the procedure will be an error. Because the interface type cannot be indexed, and there is no FullName this field.

The function of the above sentence is to convert the interface type into a pointer to []module. Base_module Pointer, M is the value after the interface is converted, OK is used to identify whether the conversion has not succeeded. This conversion is called the type assertion of Golang in Golang.

After the conversion was successful, I did a value on the converted value m, so that I could take the value of the address pointed to by the pointer. You can then manipulate the D variable as you would an array of general struct arrays.


If we don't know the type of this data parameter, but we know which field to take the value of, how should we take it?

The answer is: take the reflection and look at the following code:

Funcgetdata (datainterface{}){

  DBE. Limit(3). Find(data) 
&NBSP;&NBSP;&NBSP;&NBSP;  m  :=    reflect Valueof ( data Elem ()   
&NBSP;&NBSP;&NBSP;&NBSP;  for    i< Span style= "COLOR: #ff00dc" >  :=    0  ;    i  <    m Len ();    i++    Span style= "COLOR: #bbbbbb" >{  
  fmt. Println(m. Index(i). Fieldbyname("Fullname")) 
    }
}
Change the Getdataz function to this, and the result is the same as the code above. For the above reflection, we need to pay attention to, must be in reflect. ValueOf(data) is appended with elem (), otherwise an error will be given. The function of Elem is to obtain the value of the address pointed to by the pointer, which is equivalent to the * operator. So if the passed parameter is not a pointer, but an entity, then do not use the Elem () function.

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.