11.3.md 2.6 KB

11.3 ���Ͷ��ԣ���μ���ת���ӿڱ���������

һ���ӿ����͵ı��� varI �п��԰����κ����͵�ֵ��������һ�ַ�ʽ��������� ��̬ ���ͣ�������ʱ�ڱ����д洢��ֵ��ʵ�����͡���ִ�й����ж�̬���Ϳ��ܻ�������ͬ�����������ǿ��Է�����ӿڱ������������͡�ͨ�����ǿ���ʹ�� ���Ͷ��� ��������ij��ʱ�� varI �Ƿ�������� T ��ֵ��

    v := varI.(T)       // unchecked type assertion

varI������һ���ӿڱ���������������ᱨ����invalid type assertion: varI.(T) (non-interface type (type of varI) on left) ��

���Ͷ��Կ�������Ч�ģ���Ȼ�������ᾡ�����ת���Ƿ���Ч��������������Ԥ�����еĿ����ԡ����ת���ڳ�������ʱʧ�ܻᵼ�´�����������ȫ�ķ�ʽ��ʹ��������ʽ���������Ͷ��ԣ�

if v, ok := varI.(T); ok {  // checked type assertion
    Process(v)
    return
}
// varI is not of type T

���ת���Ϸ���v �� varI ת�������� T��ֵ��ok ���� true������ v ������ T ����ֵ��ok �� false��Ҳû������ʱ��������

Ӧ������ʹ������ķ�ʽ���������Ͷ�����

��������£����ǿ���ֻ������ if �в���һ�� ok ��ֵ����ʱʹ�����µķ����������ģ�

if _, ok := varI.(T); ok {
    // ...
}

TODO ??��In this form shadowing the variable varI by giving varI and v the same name is sometimes done.

ʾ�� 11.4 type_interfaces.go

package main

import (
	"fmt"
	"math"
)

type Square struct {
	side float32
}

type Circle struct {
	radius float32
}

type Shaper interface {
	Area() float32
}

func main() {
	var areaIntf Shaper
	sq1 := new(Square)
	sq1.side = 5

	areaIntf = sq1
	// Is Square the type of areaIntf?
	if t, ok := areaIntf.(*Square); ok {
		fmt.Printf("The type of areaIntf is: %T\n", t)
	}
	if u, ok := areaIntf.(*Circle); ok {
		fmt.Printf("The type of areaIntf is: %T\n", u)
	} else {
		fmt.Println("areaIntf does not contain a variable of type Circle")
	}
}

func (sq *Square) Area() float32 {
	return sq.side * sq.side
}

func (ci *Circle) Area() float32 {
	return ci.radius * ci.radius * math.Pi
}

�����

The type of areaIntf is: *main.Square
areaIntf does not contain a variable of type Circle

�������ж�����һ�������� Circle����Ҳʵ���� Shaper �ӿڡ� t, ok := areaIntf.(*Square); ok ���� areaIntf ���Ƿ�һ������ 'Square' ���͵ı����������ȷ���ģ�Ȼ�����Dz������Ƿ����һ�� 'Circle' ���͵ı���������Ƿ񶨵ġ�

��ע

������� areaIntf.(*Square) �е� * �ţ��ᵼ�±������impossible type assertion: Square does not implement Shaper (Area method has pointer receiver)��

����