golang 笔记9 结构体
type
type myInt int
type youInt = int
func TestType(t *testing.T) {
var x myInt = 100
var y youInt = 100
fmt.Printf("%T\n", x)
fmt.Printf("%T\n", y)
}
struct 结构体
- 函数内部使用
func TestStruct1(t *testing.T) {
var x struct {
idNo string
name string
}
x.idNo = "340001"
x.name = "Jony"
fmt.Println(x)
}
- 结构体 + 自定义类型
type Person struct {
idNo string
name string
profession string
age int
birthday time.Time
}
type office struct {
persons []Person
}
const YYYY_MM_DD = "2006-01-02"
func getTime(timeString string) time.Time {
t, _ := time.Parse(YYYY_MM_DD, timeString)
return t
}
func (p Person) printPerson() {
fmt.Println(p.idNo, p.name, p.profession, p.age, (&p.birthday).Format(YYYY_MM_DD))
}
func TestStruct2(t *testing.T) {
var person1 Person
person1.idNo = "341993001"
person1.name = "morningcat"
person1.profession = "golang工具人"
person1.birthday = getTime("1993-04-05")
person1.age = 28
person1.printPerson()
}
- 值拷贝
func changeName(p Person) {
p.name = "hello"
}
func changeName2(p *Person) {
(*p).name = "hello"
}
func TestStruct3(t *testing.T) {
var person Person
person.name = "morningcat"
changeName(person)
fmt.Println(person.name)
changeName2(&person)
fmt.Println(person.name)
}
func TestStruct4(t *testing.T) {
var person *Person = new(Person)
changeName2(person)
fmt.Println(person.name)
}
- 初始化方式
func TestStruct5(t *testing.T) {
var person3 = Person{idNo: "3419901", name: "mengzhang6", profession: "java", age: 28, birthday: getTime("1993-12-01")}
person3.printPerson()
var person4 = Person{
idNo: "3419901",
name: "mengzhang6",
profession: "java",
age: 28,
birthday: getTime("1993-12-01"),
}
person4.printPerson()
var person5 = Person{"3419901", "mengzhang6", "java", 28, getTime("1993-12-01")}
person5.printPerson()
}
- 作用于特定类型的函数
func NewPerson(idNo, name string) *Person {
return &Person{idNo: idNo, name: name}
}
func (p Person) GetPersonStr() string {
return fmt.Sprintf(p.idNo, p.name, p.profession, p.age, (&p.birthday).Format(YYYY_MM_DD))
}
func TestStruct6(t *testing.T) {
var p *Person = NewPerson("3419002", "morningcat")
fmt.Println(p.GetPersonStr())
}
func (p *Person) ChangrPersonName(name string) {
p.name = name
}
func TestStruct7(t *testing.T) {
var p = NewPerson("3419002", "morningcat")
fmt.Println(p.name)
p.ChangrPersonName("world")
fmt.Println(p.name)
}
func (x myInt) helloInt() {
fmt.Printf("Hello %d\n", x)
}
func TestStruct8(t *testing.T) {
var x myInt = 12
x.helloInt()
}
func TestStruct9(t *testing.T) {
var x int32 = 12
var y = int32(12)
fmt.Println(x, y)
}