Skip to content

Instantly share code, notes, and snippets.

@tomtsang
Created February 11, 2018 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomtsang/d97004bd3c5f75cc38c9109ebff5fb8f to your computer and use it in GitHub Desktop.
Save tomtsang/d97004bd3c5f75cc38c9109ebff5fb8f to your computer and use it in GitHub Desktop.
golang-interface-methodset.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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment