Shadow
golang实现的对象的构造函数
golang实现的对象的构造函数
package main
import (
"fmt"
)
type Address struct {
city string
area string
}
type Person struct {
name,job string
age uint8
height float32
Address //变量提升
}
func main(){
var a1 = newPerson("a1",16,180.5)
var a2 = newPerson("a2",26,170.5)
a1.job = "PHP"
a2.job = "MYSQL"
a1.talk("GOlang") //a1 擅长:PHP,现在正在学习:GOlang,奋斗吧~
a2.talk("GOlang") //a2 擅长:MYSQL,现在正在学习:GOlang,奋斗吧~
a1.sleep() //a1已经16岁了,要睡觉了~
a2.sleep() //a2已经26岁了,要睡觉了~
}
//go实现的构造函数
func newPerson(name string,age uint8,height float32) *Person{
return &Person{
name:name,
age:age,
height: height,
}
}
//Person 的talk方法
func (p Person) talk(msg string) {
fmt.Printf("%s 擅长:%s,现在正在学习:%s,奋斗吧~\n",p.name,p.job,msg)
}
//Person 的睡觉方法
func (p Person) sleep() bool{
fmt.Printf("%s已经%d岁了,要睡觉了~\n",p.name,p.age)
return true
}
Dcr163的博客
http://dcr163.cn/584.html(转载时请注明本文出处及文章链接)