Golang | Go 语言 编程练习 100题

怎样判断interface{}所属类型

interface类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。空interface(interface{})不包含任何的method,正因为如此,所有的类型都实现了空interface。

我们知道interface的变量里面可以存储任意类型的数值(该类型实现了interface)。那么我们怎么反向知道这个变量里面实际保存了的是哪个类型的对象呢?

方法1:

Go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T),这里value就是变量的值,ok是一个bool类型,element是interface变量,T是断言的类型。

        if value, ok := element.(int); ok {
            fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
        } else if value, ok := element.(string); ok {
            fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
        } else if value, ok := element.(Person); ok {
            fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
        } else {
            fmt.Println("list[%d] is of a different type", index)
        }

方法2:
switch语法

			switch value := element.(type) {
            case int:
                fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
            case string:
                fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
            case Person:
                fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
            default:
                fmt.Println("list[%d] is of a different type", index)
        }

在golang中将Json.Number转换为int / int64 / float64

我有一个变量数据,它是一个接口。 当我打印其类型时,将其获取为json.Number。 如何将强制类型转换为int / int64 / float64

查看此文档以了解json.Number上的可用方法:
https://golang.org/pkg/encoding/json/#Number

f, err := data.(json.Number).Float64()

golang怎样实现枚举类型

go语言并没有提供enum的定义,我们可以使用const来模拟枚举类型。

type PolicyType int32

const (
    Policy_MIN      PolicyType = 0
    Policy_MAX      PolicyType = 1
    Policy_MID      PolicyType = 2
    Policy_AVG      PolicyType = 3
)

这里定义了一个新的类型PolicyType,并且定义了4个常量(Policy_MIN, Policy_MAX, Policy_MID, Policy_AVG),类型是PolicyType。

你可能感兴趣的:(golang100题,golang,开发语言,后端)