其他分享
首页 > 其他分享> > golang中struct

golang中struct

作者:互联网

package main

import "fmt"

type person struct {
	name string
	age  int
}

func Older(p1, p2 person) (person, int) {
	if p1.age > p2.age {
		return p1, p1.age - p2.age
	}
	return p2, p2.age - p1.age
}
func main() {
	var tom person
	tom.name, tom.age = "tom", 18
	bob := person{age: 25, name: "bob"}
	paul := person{"Paul", 43}
	tb_Older, tb_diff := Older(tom, bob)
	tp_Older, tp_diff := Older(tom, paul)
	bp_Older, bp_diff := Older(bob, paul)
	fmt.Printf("Of %s and %s ,%s is older by %d years\n", tom.name, bob.name, tb_Older.name, tb_diff)
	fmt.Printf("Of %s and %s,%s is older by %d years\n", tom.name, paul.name, tp_Older.name, tp_diff)
	fmt.Printf("Of %s and %s,%s is older by %d years\n", bob.name, paul.name, bp_Older.name, bp_diff)
}

结构体声明的,有几种方法

按照顺序提供初始化值

p := person{"tom",25}

通过field:value的方法初始化,这样可以任意顺序

p := person{age:24 ,name:"tom"}

通过new函数分配一个指针,此处P的类型为*person

p:=new(person)

比较两个人的年龄,返回年龄大的那个人,并且返回年龄查,struct也是传值的

 

标签:struct,Older,age,golang,person,tom,diff,name
来源: https://blog.csdn.net/ens160/article/details/119278696