当前位置:   article > 正文

Golang interface互相转换_golang interface转interface

golang interface转interface

1、Golang的interface类型的值之间互相转换

1.1、下面来一段代码

package main

import "fmt"

type IParent interface {
	Sing()
}

type ISon interface {
	IParent
	Play()
}

type Son struct {
}

type Parent struct {
}

func (s *Son) Play() {
	fmt.Println("play")
}

func (s *Son) Sing() {
	fmt.Println("son sing")
}

func (p *Parent) Sing() {
	fmt.Println("parent sing")
}

func main() {
	var ison ISon
	var son = &Son{}
	ison = son
	var ip IParent
	var p = &Parent{}
	ip = p
	_, ok := ison.(IParent)
	if ok {
		fmt.Println("son to parent ok")
	}
	_, ok = ip.(ISon)
	if ok {
		fmt.Println("parent to son ok")
	}
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

1.2、执行结果

son to parent ok
  • 1

1.3、结论

子类向父类转化成功,父类向子类转化失败。因为子类具备父类的全部特征,但是父类却不一定具备子类的特征。所以可以理解为只能向上强转,不能向下强转。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/907832
推荐阅读
相关标签
  

闽ICP备14008679号