Created
May 13, 2019 10:55
-
-
Save ochaton/8e740fca023bfda7d3e0f47e0ac10561 to your computer and use it in GitHub Desktop.
Learning Go interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type IFace interface { | |
Method() string | |
} | |
func TakingObject(i IFace) { | |
fmt.Println(i.Method()) | |
} | |
func TakingPointer(p *IFace) { | |
fmt.Println((*p).Method()) | |
// fmt.Println(p.Method()) --> compilation error: p.Method undefined (type *IFace is pointer to interface, not interface) | |
} | |
type Foo struct { | |
C int | |
} | |
func (f Foo) Method() string { | |
f.C += 1 | |
return fmt.Sprintf("Foo: plain: %d", f.C) | |
} | |
type Bar struct { | |
C int | |
} | |
func (b *Bar) Method() string { | |
b.C += 1 | |
return fmt.Sprintf("Bar: pointer %d", b.C) | |
} | |
func main() { | |
f1 := Foo{} | |
// f1 is copied when transmitted to func | |
TakingObject(f1) // -> Foo: plain: 1 | |
TakingObject(f1) // -> Foo: plain: 1 | |
// TakingPointer(f1) --> compilation error: cannot use f1 (type Foo) as type *IFace in argument to TakingPointer: | |
// *IFace is pointer to interface, not interface | |
TakingObject(&f1) // -> Foo: plain: 1 | |
TakingObject(&f1) // -> Foo: plain: 1 | |
// TakingPointer(&f1) --> compilation error: cannot use &f1 (type *Foo) as type *IFace in argument to TakingPointer: | |
// *IFace is pointer to interface, not interface | |
b1 := Bar{} | |
// TakingObject(b1) --> compilation error: cannot use b1 (type Bar) as type IFace in argument to TakingObject: | |
// Bar does not implement IFace (Method method has pointer receiver) | |
// TakingPointer(b1) --> compilation error: cannot use b1 (type Bar) as type *IFace in argument to TakingPointer: | |
// *IFace is pointer to interface, not interface | |
TakingObject(&b1) // -> Bar: pointer 1 | |
TakingObject(&b1) // -> Bar: pointer 2 | |
// TakingPointer(&b1) --> compilation error: cannot use &b1 (type *Bar) as type *IFace in argument to TakingPointer: | |
// *IFace is pointer to interface, not interface | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment