mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 01:21:38 +08:00
fix: coding style and file format for all example.
This commit is contained in:
@@ -1,48 +1,49 @@
|
||||
// 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 function argument:
|
||||
// List does not implement Appender (Append method requires pointer receiver)
|
||||
// CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
|
||||
|
||||
if LongEnough(lst) { // VALID: Identical receiver type
|
||||
fmt.Printf(" - lst is long enough")
|
||||
}
|
||||
|
||||
// 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") // - plst is long enoug
|
||||
}
|
||||
}
|
||||
// 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 function argument:
|
||||
// List does not implement Appender (Append method requires pointer receiver)
|
||||
// CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
|
||||
|
||||
if LongEnough(lst) { // VALID: Identical receiver type
|
||||
fmt.Printf(" - lst is long enough")
|
||||
}
|
||||
|
||||
// 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") // - plst is long enoug
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user