代码改变世界

Golang中的struct

2013-04-04 23:16  Yang-Onion  阅读(383)  评论(0编辑  收藏  举报
package main

import (
    "fmt"
)

func main() {
    var tom Person
    tom.name = "Tom"
    tom.age = 26
    fmt.Printf("my name is %s,I'm %d years old\n", tom.name, tom.age)

    //按顺序赋值
    jim := Person{"Jim", 25}
    fmt.Printf("my name is %s,I'm %d years old\n", jim.name, jim.age)

    //field:value赋值,可不按顺序
    lucy := Person{age: 23, name: "Lucy"}
    fmt.Printf("my name is %s,I'm %d years old\n", lucy.name, lucy.age)

    older, olderage := OlderPerson(tom, jim)
    fmt.Printf("the older person is %s,old age is %d\n", older.name, olderage)

    lily := Employee{Human: Human{"Lily", 23, "13883987410"}, string: "5", phone: "15920580257"}
    fmt.Printf("my name is %s,my age is %d,i have %s friends and my PhoneNumber is%s\n", lily.name, lily.age, lily.string, lily.phone)
    fmt.Printf("my name is %s,my age is %d,i have %s friends and my other PhoneNumber is%s", lily.name, lily.age, lily.string, lily.Human.phone)
}

//struct
type Person struct {
    name string
    age  int
}

func OlderPerson(p1, p2 Person) (Person, int) {
    if p1.age > p2.age {
        return p1, p1.age - p2.age
    }
    return p2, p2.age - p1.age
}

//struct匿名字段:只提供类型,而不写字段名的方式,也就是匿名字段,也称为嵌入字段。
type Human struct {
    name  string
    age   int
    phone string
}

//Employee中有phone,Human中也有phone,默认访问最外层的,即Employee中的phone,
//如果要访问Human中的phone请使用Employee.Human.phone
type Employee struct {
    Human
    string
    phone string
}

 

home page tracking
NutriSystem Diet