11.6.md 2.4 KB

11.6 ʹ�÷�������ӿ�

�� 10.6.3 ������ methodset1.go �����ǿ����������ڱ����ϵķ���ʵ�����Dz����ֱ���������ָ�뻹��ֵ�ġ��������ӿ�����ֵʱ��������е㸴�ӣ�ԭ���ǽӿڱ����д洢�ľ���ֵ�Dz���Ѱַ�ģ����˵��ǣ����ʹ�ò�����������������󡣿�������ij���

ʾ�� 11.5 methodset2.go:

package main

import (
	"fmt"
)

type List []int

func (l List) Len() int {
	return len(l)
}

func (l *List) Append(val int) {
	*l = append(*l, val)
}

type Appender interface {
	Append(int)
}

func CountInto(a Appender, start, end int) {
	for i := start; i <= end; i++ {
		a.Append(i)
	}
}

type Lener interface {
	Len() int
}

func LongEnough(l Lener) bool {
	return l.Len()*10 > 42
}

func main() {
	// A bare value
	var lst List
	// compiler error:
	// cannot use lst (type List) as type Appender in argument to CountInto:
	//       List does not implement Appender (Append method has pointer receiver)
	// CountInto(lst, 1, 10)
	if LongEnough(lst) { // VALID:Identical receiver type
		fmt.Printf("- lst is long enough\n")
	}

	// A pointer value
	plst := new(List)
	CountInto(plst, 1, 10) //VALID:Identical receiver type
	if LongEnough(plst) {
		// VALID: a *List can be dereferenced for the receiver
		fmt.Printf("- plst is long enough\n")
	}
}

����

�� lst �ϵ��� CountInto ʱ�ᵼ��һ��������������Ϊ CountInto ��Ҫһ�� Appender�������ķ��� Append ֻ������ָ���ϡ� �� lst �ϵ��� LongEnough �ǿ��Ե���Ϊ 'Len' ������ֵ�ϡ�

�� plst �ϵ��� CountInto �ǿ��Եģ���Ϊ CountInto ��Ҫһ�� Appender���������ķ��� Append ������ָ���ϡ� �� plst �ϵ��� LongEnough Ҳ�ǿ��Եģ���Ϊָ��ᱻ�Զ������á�

�ܽ�

�ڽӿ��ϵ��÷���ʱ�������кͷ�������ʱ��ͬ�Ľ��������ͻ����ǿ��ԴӾ������� P ֱ�ӿ��Ա�ʶ�ģ�

  • ָ�뷽������ͨ��ָ�����
  • ֵ��������ͨ��ֵ����
  • ��������ֵ�ķ�������ͨ��ָ����ã���Ϊָ������ȱ�������
  • ��������ָ��ķ���������ͨ��ֵ���ã���Ϊ�洢�ڽӿ��е�ֵû�е�ַ

��һ��ֵ��ֵ��һ���ӿڸ�ֵʱ����������ȷ�����п��ܵĽӿڷ����������ڴ�ֵ�ϱ����ã���˲���ȷ�ĸ�ֵ�ڱ����ھͻ�ʧ�ܡ�

��ע��

Go���Թ淶�����˽ӿڷ������ĵ��ù���