Type Assertions in Go Language (Let's Go 26)

GoThe empty interface is used interface {}to indicate that it can be of any type, so that if this 变量type needs to be detected, then it is necessary 类型断言.

val,ok := varl.(Type)

valIt must be a variable of an excuse type, otherwise an error will be reported when compiling.

Typeis a concrete type.

This assertion expression returns a valand a Boolean type ok, according to okwhether varlit belongs to Typethe type.

  • If Typeit is a concrete type, the type assertion varlchecks whether the dynamic type of is equal to the concrete type Type. If the check succeeds, the result returned by the type assertion is the dynamic value varlof , whose type is Type.
  • If Typeis an interface type, the type assertion checks varlwhether the dynamic type of is satisfied Type. If the check is successful, varlthe dynamic value of is not extracted, and the return value is an interface value Typeof .
  • Regardless Typeof the type of , if varlis a nil interface value, the type assertion will fail.
package main

import (
	"fmt"
)

func main() {
    
    
	//定义一个任意类型的变量
	var site interface{
    
    }
	site = "https://qiucode.cn"

	web, ok := site.(string)

	fmt.Println(web, ok)
}

insert image description here

Type assertions can switchbe used in conjunction.

package main

import (
	"fmt"
)

func getType(t interface{
    
    }) {
    
    
	switch t.(type) {
    
    
	case string:
		fmt.Println("该类型为 string ")
	case int:
		fmt.Println("该类型是 int ")
	case float64:
		fmt.Println("该类型为 float64 ")
	default:
		fmt.Println("暂没有匹配的类型")
	}
}

func main() {
    
    
	//定义一个任意类型的变量
	var site interface{
    
    }
	site = "https://qiucode.cn"

	getType(site)
}

insert image description here

Guess you like

Origin blog.csdn.net/coco2d_x2014/article/details/127467734