package main
import "fmt"
func main() {
//创建对象,通过.方式进行初始化
a := person{}
a.name = "wyf"
a.age = 30
fmt.Println(a)
//创建对象,通过类似构造的方式进行初始化
b := person{
name: "wyff",
age: 300,
}
fmt.Println(b)
//值传递
A(b)
fmt.Println(b)
//person引用传递
fmt.Println("-------引用地址传递--------")
B(&b)
fmt.Println(b)
fmt.Println("-------初始化一个引用地址类型--------")
r := &person{
name: "xxx",
age: 100,
}
fmt.Println(r)
B(r)
fmt.Println(r)
fmt.Println("-------匿名结构--------")
ll := struct {
name string
age int
}{
name: "yyy",
age: 19,
}
fmt.Println(ll)
fmt.Println("-------嵌套匿名--------")
oo := stu{name: "bbbb", age: 300}
oo.stu1.city = "bj"
oo.stu1.phone = "1356"
fmt.Println(oo)
fmt.Println("-------匿名字段--------")
mm := gra{"hhh", 90}
fmt.Println(mm)
fmt.Println("-------相互赋值--------")
pp1 := person{name: "bbbb", age: 300}
pp2 := person{name: "bbbb", age: 300}
fmt.Println(pp1 == pp2)
pp3 := pp2
fmt.Println(pp3)
}
type person struct {
name string
age int
}
type gra struct {
string
int
}
type stu struct {
name string
age int
stu1 struct {
phone, city string
}
}
func B(per *person) {
per.age = 13
fmt.Println("per", per)
}
func A(per person) {
per.age = 13
fmt.Println("per", per)
}
{wyf 30}
{wyff 300}
per {wyff 13}
{wyff 300}
-------引用地址传递--------
per &{wyff 13}
{wyff 13}
-------初始化一个引用地址类型--------
&{xxx 100}
per &{xxx 13}
&{xxx 13}
-------匿名结构--------
{yyy 19}
-------嵌套匿名--------
{bbbb 300 {1356 bj}}
-------匿名字段--------
{hhh 90}
-------相互赋值--------
true
{bbbb 300}
组合类型
package main
import "fmt"
func main() {
a := teacher{name: "teacher"}
a.human.sex = 1
b := student{name: "student"}
b.human.sex = 2
fmt.Println(a, b)
//将human当做一个普通的字段
c := teacher{name: "teacher", human: human{sex: 1}}
d := student{name: "student", human: human{sex: 2}}
fmt.Println(c, d)
c.name = "tea"
d.name = "stu"
fmt.Println(c, d)
}
type teacher struct {
human
name string
}
type student struct {
human
name string
}
//组合类型,类似于java里面的继承
type human struct {
sex int
}
{{1} teacher} {{2} student}
{{1} teacher} {{2} student}
{{1} tea} {{2} stu}
对象的方法
package main
import "fmt"
func main() {
a := teacher{}
a.Print()
b := stu{}
b.Print()
}
//对象的方法定义一个接收者
func (a teacher) Print() {
fmt.Println("teacher的方法")
}
func (b stu) Print() {
fmt.Println("student的方法")
}
type teacher struct {
name string
}
type stu struct {
name string
}
teacher的方法
student的方法
对象的方法的地址值传递
package main
import "fmt"
func main() {
a := teacher{}
a.Print()
fmt.Println(a.name)
b := stu{}
b.Print()
fmt.Println(b.name)
}
//对象的方法引用传递
func (a *teacher) Print() {
a.name = "aaa"
fmt.Println("teacher的方法")
}
func (b stu) Print() {
b.name = "bbb"
fmt.Println("student的方法")
fmt.Println(b.name)
}
type teacher struct {
name string
}
type stu struct {
name string
}
小例子
teacher的方法
aaa
student的方法
bbb
这里输出空字符串
package main
import "fmt"
func main() {
var a TZ
a.print()
(*TZ).print(&a)
}
//int类型的TZ
type TZ int
func (tz *TZ) print() {
fmt.Println("TZ")
}
TZ
TZ
有疑问加站长微信联系(非本文作者)