If the entry of a function is interface{}, there are several ways to get the arguments:
1 FMT:
" FMT " Func Main () { V:"helloWorld" fmt. Println (typeoftypeofinterfacestring { return to FMT. Sprintf ("%T", v)}
2 Reflections:
Import ( "reflect" "fmt") Func main () { V: " Hello World " FMT. Println (typeoftypeofinterfacestring { return reflect. TypeOf (v). String ()}
3 Type Assertion:
Func Main () {V:="Hello World"FMT. Println (typeof(v))} Functypeof(VInterface{})string { SwitchT: =v. (type) { Case int: return "int" Casefloat64:return "float64" //... etc default: _ =Treturn "Unknown" }}
In fact, the first two are all used reflex, FMT. The final call in Printf ("%T") is still reflect.TypeOf() .
Func (P *pp) Printarg (ARGInterface{}, Verb rune) { ... //Special processing considerations. //%T (the value ' s type) and%p (its address) is special; we always do them first. Switchverb { Case 'T': p.fmt.fmt_s (reflect. TypeOf (ARG). String ())return Case 'P': P.fmtpointer (reflect. ValueOf (ARG),'P') return }
Reflect. The parameter of TypeOf () is v interface{} , how does the Golang reflection do?
In Golang, interface is also a struct, recording 2 pointers:
- Pointer 1, pointing to the type of the variable
- Pointer 2, which points to the value of the variable
As below, the structure of the empty interface is the above 2 pointers, the first pointer of the type is, type rtype struct non-null interface because of the need to carry more information (such as what the interface implements), so the type of the first pointer is Itab, in Itab recorded the variable dynamic type: typ *rtype .
//Emptyinterface is the header for a interface{} value.Type Emptyinterfacestruct{Typ*Rtype Wordunsafe. Pointer}//Nonemptyinterface is the header for a interface value with methods.Type Nonemptyinterfacestruct { //See .. /runtime/iface.go:/itabItab *struct{Ityp*rtype//Static interface typeTyp *rtype//Dynamic Concrete TypeLinkunsafe. Pointer bad Int32 unused int32 fun [100000]unsafe. Pointer//Method Table} Wordunsafe. Pointer}
Let's take a look at reflect. TypeOf ():
// TypeOf Returns the reflection type that represents the dynamic type of I. // If i is a nil interface value, TYPEOF returns nil. Interface {}) Type { eface:= * (*emptyinterface) (unsafe. Pointer (&i)) return totype (Eface.typ)}
typeof sees an empty interface interface{}, which translates the address of the variable to an empty interface, and then returns the resulting Rtype to the type interface. It is important to note that when calling reflect. Prior to TypeOf, an implicit type conversion has occurred, with the conversion of a specific type of NULL interface. This process is relatively simple, as long as the copy typ *rtype and word unsafe.Pointer can be.
For example w := os.Stdout , the interface value of the variable is the same in memory:
So for the third, how does the type assertion determine if it is an interface? Back in the first place, in Golang, the interface is a loosely coupled concept, whether a type implements an interface or not, which is to see if the type implements all the functions required by the interface, so the method of type assertion is to check that the type implements all the functions required by the interface.
Day k8s code, you can see the use of more types of assertions:
Func leastrequestedprioritymap (pod *api. Pod, MetaInterface{}, NodeInfo *Schedulercache. NodeInfo) (Schedulerapi. Hostpriority, error) {varNonzerorequest *Schedulercache. ResourceifPrioritymeta, OK: = Meta. (*prioritymetadata); OK {nonzerorequest=Prioritymeta.nonzerorequest}Else { //We couldn ' t parse metadata-fallback to computing it.Nonzerorequest =getnonzerorequests (pod)}returncalculateunusedpriority (pod, nonzerorequest, NodeInfo)}
The implementation of the type assertion is in Src/runtime/iface.go (?), but this code is not understood, and then updated later.
Func Asserti2i2 (Inter *interfacetype, I iface) (R iface, bBOOL) {tab:=I.tabiftab = =Nil {return } ifTab.inter! =Inter {tab= Getitab (Inter, Tab._type,true) iftab = =Nil {return}} r.tab=tab R.data=I.data b=true return}func Asserte2i2 (Inter*interfacetype, E Eface) (R iface, bBOOL) {t:=E._typeift = =Nil {return} tab:= Getitab (Inter, T,true) iftab = =Nil {return} r.tab=tab R.data=E.data b=true return}
查看原文地址