首页 > 其他分享 >Go - Type assertions and Type switches

Go - Type assertions and Type switches

时间:2024-02-21 21:45:10浏览次数:26  
标签:case type value switches interface switch expression Go Type

Type assertions

For an expression x of interface type, but not a type parameter, and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

If the type assertion holds, the value of the expression is the value stored in x and its type is T. If the type assertion is false, a run-time panic occurs. In other words, even though the dynamic type of x is known only at run time, the type of x.(T) is known to be T in a correct program.

var x interface{} = 7          // x has dynamic type int and value 7
i := x.(int)                   // i has type int and value 7

type I interface { m() }

func f(y I) {
	s := y.(string)        // illegal: string does not implement I (missing method m)
	r := y.(io.Reader)     // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
	…
}

A type assertion used in an assignment statement or initialization of the special form

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool

yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case.

 

Type switches

A type switch compares types rather than values. It is otherwise similar to an expression switch. It is marked by a special switch expression that has the form of a type assertion using the keyword type rather than an actual type:

switch x.(type) {
// cases
}

Cases then match actual types T against the dynamic type of the expression x. As with type assertions, x must be of interface type, but not a type parameter, and each non-interface type T listed in a case must implement the type of x. The types listed in the cases of a type switch must all be different.

TypeSwitchStmt  = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
TypeCaseClause  = TypeSwitchCase ":" StatementList .
TypeSwitchCase  = "case" TypeList | "default" .

The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the end of the TypeSwitchCase in the implicit block of each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.

Instead of a type, a case may use the predeclared identifier nil; that case is selected when the expression in the TypeSwitchGuard is a nil interface value. There may be at most one nil case.

Given an expression x of type interface{}, the following type switch:

switch i := x.(type) {
case nil:
	printString("x is nil")                // type of i is type of x (interface{})
case int:
	printInt(i)                            // type of i is int
case float64:
	printFloat64(i)                        // type of i is float64
case func(int) float64:
	printFunction(i)                       // type of i is func(int) float64
case bool, string:
	printString("type is bool or string")  // type of i is type of x (interface{})
default:
	printString("don't know the type")     // type of i is type of x (interface{})
}

 

标签:case,type,value,switches,interface,switch,expression,Go,Type
From: https://www.cnblogs.com/zhangzhihui/p/18026272

相关文章

  • Go - wrap an error
        ......
  • Go - panic
        ......
  • Go - argument evaluation with defer
        ......
  • golang指针和结构体
    指针指针操作指针包括指针地址、指针类型和指针取值&:&符号放在变量前面进行取地址操作**:*放在变量前面根据地址进行取值指针地址:funcmain(){ varaint=1 //a的值是1--类型是int--,地址是0xc0000120c0,&是地址符号 fmt.Printf("a的值是%v--类型是%T--,地......
  • Go语言精进之路读书笔记第31条——优先考虑并发设计
    31.1并发与并行1.并行方案在处理器核数充足的情况下启动多个单线程应用的实例2.并发方案重新做应用结构设计,即将应用分解成多个在基本执行单元(例如操作系统线程)中执行的、可能有一定关联关系的代码片段goroutine:由Go运行时负责调度的用户层轻量级线程,相比传统操作系统线程而......
  • Go 100 mistakes - #45: Returning a nil receiver
        We’veseeninthissectionthatinGo,havinganilreceiverisallowed,andaninterfaceconvertedfromanilpointerisn’tanilinterface.Forthatreason,whenwehave toreturnaninterface,weshouldreturnnotanilpointerbuta......
  • django常用命令
    常用命令任务命令创建新项目django-admin.pystartprojectproject_name(注意:windows系统下请用django-adminstartprojectproject_name)创建新应用pythonmanage.pystartappapp_name(注意:你需要先cd进入创建的项目文件夹)检测模型变换,生成数据库同步脚......
  • Go - named result parameters
           ......
  • Go 100 mistakes - #42: Not knowing which type of receiver to use
          ......
  • gorm入门
    目录1.简介2.实例3.增删改查新增更新删除查询高级查询原生sql4.模型类约定字段标签关联标签单个声明BelongsTo一对一HasOne一对一一对多多对多文档1.简介特定: 全功能ORM 关联(HasOne,HasMany,BelongsTo,ManyToMany,多态,单表继承) Create,Save,Update,Delete,Find中钩子方......