Golang 接口与多态

Jackey Golang 3,176 次浏览 , , 没有评论
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package main
import (
"fmt"
)
type A interface {
Get()
}
type B struct {
}
func (b *B) Get () {
fmt.Println("b")
}
type C struct {
}
func (c *C) Get () {
fmt.Println("c")
}
func main() {
var a A = &B{}
a.Get()
var aa A = &C{}
aa.Get()
}
package main import ( "fmt" ) type A interface { Get() } type B struct { } func (b *B) Get () { fmt.Println("b") } type C struct { } func (c *C) Get () { fmt.Println("c") } func main() { var a A = &B{} a.Get() var aa A = &C{} aa.Get() }
package main

import (
  "fmt"
)

type A interface {
  Get()
}

type B struct {
}

func (b *B) Get ()  {
  fmt.Println("b")
}

type C struct {
}

func (c *C) Get ()  {
  fmt.Println("c")
}


func main()  {
  var a A = &B{}
  a.Get()
  var aa A = &C{}
  aa.Get()
}

输出结果:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
b
c
b c
b
c

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Go