当前位置:网站首页>Golang type assertion
Golang type assertion
2022-06-23 23:43:00 【Don't rob me of my spicy strip~】
One , How to detect and convert the types of interface variables
stay Go Linguistic interface Can be of any type , therefore Go The type assertion is given to judge the type contained in the interface at a certain time , For example, now give an interface , be known as InterfaceText:
x,err:=interfaceText.(T)//T Is a certain type
The above formula is the general form of interface assertion , Because this method may not work well every time , therefore err The function of is to judge whether something is wrong . So general interface assertions are often written as follows :
if v,err:=InterfaceText.(T);err {//T It's a type of
possess(v)// Handle v
return
}If the conversion is legal , be v by InterfaceText Convert to type T Value ,err by ture, conversely err by false.
It is worth noting that :InterfaceText Must be an interface type !!!
Sometimes if you just want to judge whether there are types T, Can be written as :
if _,err:=InterfaceText.(T);err{
//..
return
}Here is a specific example to help understand :
package main
import (
"fmt"
"math"
)
type Square struct{
slide float32
}
type Circle struct{
radius float32
}
type Figure interface{
Area() float32
}
func main(){
var fi Figure
sq:=new(Square)
sq.slide=5
fi=sq
if v,err:=fi.(*Square);err {
fmt.Printf("fi contain a variable of type : %v\n",v)
}else {
fmt.Println("fi does not contain a variable of Square")
}
if v2,ok:=fi.(*Circle);ok {
fmt.Printf("fi contain a variable of type : %v\n",v2)
}else {
fmt.Println("fi does not contain a variable of Circle")
}
}
func (s *Square) Area() float32{
return s.slide*s.slide
}
func (c *Circle) Area() float32{
return c.radius*c.radius*math.Pi
}Running results :

Two , Type judgment :type-switch
This is another type of judgment , This method and switch Very similar . Look directly at the code :
switch x:=InterfaceText.(type) {
case *Square:
fmt.Printf("text:%v",i)
case *Circle:
//..
case nil:
//..
default:
//..
//..and so forth
}Understanding ideas and switch Very similar , If InterfaceText There is *Square,*Circle,nil Three types of , The corresponding code will be executed , If none of them , Will perform default Code in .
If only judge , Instead of using a value, it can be written as :
switch InterfaceText.(type) {
case *Square:
fmt.Printf("text:%v",i)
case *Circle:
//..
case nil:
//..
default:
//..
//..and so forth
}Sometimes for convenience , We can package it into a function to judge some unknown types :
func classify(items...interface{}){
for i,x:=range items {
switch x.(type) {
case bool:
fmt.Printf("text:%v",i)
case int:
//..
case float32:
//..
default:
//..
//..and so forth
}
}
} You can call this method like this :classifier(13, -14.3, false) .
Of course, other types can also be added , It depends on the specific situation .
ending~~
边栏推荐
猜你喜欢

高仿書旗小說 Flutter 版,學起來

Is the geTx status management in the flutter really so good to use?

One person even broke up a Netease cloud music Cloud Village

CTF—Go题目复现
![[design] 1359- how umi3 implements plug-in architecture](/img/f1/c4cb7715aff7f10d099e4f11b32c01.png)
[design] 1359- how umi3 implements plug-in architecture

Flutter中的GetX状态管理用起来真的那么香吗?

谈谈数字化转型晓知识
Androidkotlin comprehensive and detailed class usage grammar learning guide

High imitation Book flag novel flutter edition, learn it

WebService client request failed can not create a secure xmlinputfactory
随机推荐
国内外最好的12款项目管理系统优劣势分析
Thinking (86): master-slave realization idea
Autofac详解
【HackTheBox】Fawn
Why can't the netherworld fortress machine be remotely connected to the server? What are the ways to solve such problems?
一个人竟然撸了一个微博 APP
STM32-------外部中断
What to check for AIX system monthly maintenance (II)
Image segmentation - data annotation
【HackTheBox】 meow
Construction of cache stack FIFO in different application scenarios for PLC data operation series (detailed algorithm explanation)
PLC数据操作系列之构造不同应用场景的缓存栈FIFO(算法详解)
STM32------ADC(电压检测)
抖音支付十万级 TPS 流量发券实践
[observation] Dell technology + Intel aoteng Technology: leading storage innovation with "nanosecond speed"
Cause analysis and Countermeasures for FANUC robot srvo-050 collision detection alarm (available for personal test)
网站如何在Google建立索引
1004. 最大连续1的个数 III ●●
Sorry, your USB cable may be wrong!
PyQt5_ Qtablewidget paging radio right-click menu control