zoukankan      html  css  js  c++  java
  • Golang中的struct Yang

    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
    }
  • 相关阅读:
    Access-自定义控件TabControl
    Excel公式-求最低价网站名字
    Excel图表-太极图
    Excel图表-"DNA"图
    VB中的GDI编程-2 画笔
    leetcode
    leetcode
    leetcode
    leetcode
    leetcode
  • 原文地址:https://www.cnblogs.com/Yang2012/p/3000285.html
Copyright © 2011-2022 走看看