1 Star 0 Fork 0

叶明志/golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.go 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2019-06-30 10:40 +08:00 . 借口的使用
package main
import (
"fmt"
"math/rand"
)
type Student struct {
Name string
Age int
}
func (p *Student) init(Name string, Age int) {
p.Name = Name
p.Age = Age
}
func (p *Student) String() string {
str := fmt.Sprintf("name=%s,age=%d\n", p.Name, p.Age)
return str
}
func testString() { //String接口的实现
var stu *Student = new(Student)
stu.Name = "hu"
stu.Age = 23
fmt.Printf("%s", stu)
}
type Test interface {
Print()
Sleep()
}
func (p *Student) Print() {
fmt.Printf("name=%s,age=%d\n", p.Name, p.Age)
}
func (p *Student) Sleep() {
fmt.Printf("I am sleeping for %f minutes\n", rand.Float32()*60)
}
func testInterface() {
// var t Test=&Student{
// Name:"zhang",
// Age:25,
// }
var t Test
var stu *Student = new(Student)
stu.Name = "zhang"
stu.Age = 25
t = stu
t.Print()
t.Sleep()
}
type People struct {
Name string
Age int
}
func (people *People) Print() {
fmt.Printf("name=%s,age=%d\n", people.Name, people.Age)
}
func (people *People) Sleep() {
fmt.Printf("I am sleeping for %f minutes\n", rand.Float32()*60)
}
func testInterface2() { //借口里面有方法,可以实现(含有这个借口所有方法的 )结构体
var people *People = &People{
Name: "zhou",
Age: 34,
}
var t Test
t = people
t.Print()
t.Sleep()
}
func PrintInterface() { //借口是个指针
var t Test
fmt.Println(t)
}
type Test2 interface { //借口可以嵌套
Test
Eat()
}
func (people *People) Eat() {
fmt.Println("I am having breakfast.")
}
func testInterface3() {
var people *People = &People{
Name: "sun",
Age: 35,
}
var t Test = people
var t2 Test2 = people
t.Sleep()
t.Print()
t2.Sleep()
t2.Print()
t2.Eat()
}
func main() {
// var p *Student = new(Student)
// p.init("hu", 23)
// fmt.Println(*p)
// testString()
// testInterface()
// testInterface2()
// PrintInterface()
testInterface3()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助