浅谈Go语言中的结构体struct & 接口Interface & 反射

2020-01-28 12:28:52王振洲

Interface嵌套

一个接口可以嵌套在另外的接口。

即需要实现2个接口的方法。


type Car interface {
 NameGet() string
 Run(n int)
 Stop()
}

type Used interface {
 Car
 Cheap()
}

类型断言

类型断言,由于接口是一般类型,不知道具体类型,

如果要转成具体类型,可以采用以下方法进行转换:


var t int
var x interface{}
x = t

y = x.(int)  //转成int
y, ok = x.(int) //转成int,不报错

栗子一:


func test(i interface{}) {
 // n := i.(int)
 n, ok := i.(int)
 if !ok {
  fmt.Println("error")
  return
 }
 n += 10
 fmt.Println(n)
}

func main() {
 var t1 int
 test(t1)
}

栗子二:


switch & type


type Student struct {
 Name string
}

func judgmentType(items ...interface{}) {
 for k, v := range items {
  switch v.(type) {
  case string:
   fmt.Printf("string, %d[%v]n", k, v)
  case bool:
   fmt.Printf("bool, %d[%v]n", k, v)
  case int, int32, int64:
   fmt.Printf("int, %d[%v]n", k, v)
  case float32, float64:
   fmt.Printf("float, %d[%v]n", k, v)
  case Student:
   fmt.Printf("Student, %d[%v]n", k, v)
  case *Student:
   fmt.Printf("Student, %d[%p]n", k, v)
  }
 }
}

func main() {
 stu1 := &Student{Name: "nick"}
 judgmentType(1, 2.2, "learing", stu1)
}

栗子三:

判断一个变量是否实现了指定接口


type Stringer interface {
 String() string
}

type Mystruct interface {

}
type Mystruct2 struct {

}
func (this *Mystruct2) String() string {
 return ""
}

func main() {
 var v Mystruct
 var v2 Mystruct2
 v = &v2

 if sv, ok := v.(Stringer); ok {
  fmt.Printf("%v implements String(): %sn", sv.String());
 }
}

反射 reflect

reflect包实现了运行时反射,允许程序操作任意类型的对象。

典型用法是用静态类型interface{}保存一个值,

  通过调用TypeOf获取其动态类型信息,该函数返回一个Type类型值。

  调用ValueOf函数返回一个Value类型值,该值代表运行时的数据。

func TypeOf(i interface{}) Type

TypeOf返回接口中保存的值的类型,TypeOf(nil)会返回nil。

func ValueOf(i interface{}) Value

ValueOf返回一个初始化为i接口保管的具体值的Value,ValueOf(nil)返回Value零值。

reflect.Value.Kind

获取变量的类别,返回一个常量


const (
 Invalid Kind = iota
 Bool
 Int
 Int8
 Int16
 Int32
 Int64
 Uint
 Uint8
 Uint16
 Uint32
 Uint64
 Uintptr
 Float32
 Float64
 Complex64
 Complex128
 Array
 Chan
 Func
 Interface
 Map
 Ptr
 Slice
 String
 Struct
 UnsafePointer
)

reflect.Value.Kind()方法返回的常量

reflect.Value.Interface()

转换成interface{}类型

【变量<-->Interface{}<-->Reflect.Value】