Golang Day3
Interface
- 作為泛用型別使用
- 作為 OOP 方式使用
泛用型別
package main
import(
"fmt"
)
var (
a,b,c interface{}
)
func main(){
a = 123
b = 123.4
c = "this is interface test"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
OOP 方式
package main
import(
"fmt"
)
type Skill interface{
GetName() string
GetSkill() string
}
func ShowInfo(s Skill){
fmt.Printf("%s,%s",s.GetName(),s.GetSkill())
}
type Dog struct{
name string
skill string
}
func (d *Dog) GetName() string{
return d.name
}
func (d *Dog) GetSkill() string{
return d.skill
}
type Cat struct{
name string
skill string
}
func (c *Cat) GetName() string{
return c.name
}
func (c *Cat) GetSkill() string{
return c.skill
}
func main(){
dog:=&Dog{
name:"my name is black",
skill:"I can jump",
}
cat:=&Cat{
name:"my name is white",
skill:"I can eat",
}
fmt.Println(dog)
fmt.Println(cat)
ShowInfo(dog)
var abc interface{}
abc = dog
fmt.Println(abc) //&{my name is black I can jump}
fmt.Println(&abc) //0x40c128
fmt.Println(abc.(*Dog)) //&{my name is black I can jump}
ShowInfo(abc.(Skill)) //my name is black,I can jump
}
0 意見