zoukankan      html  css  js  c++  java
  • 73_Go基础_1_40 结构体嵌套与传值

    package main
    
    import "fmt"
    
    // 1.定义一个书的结构体
    type Book struct {
        bookName string
        price    float64
    }
    
    // 2.定义学生的结构体
    type Student struct {
        name string
        age  int
        book Book // 结构体嵌套
    }
    
    type Student2 struct {
        name string
        age  int
        book *Book // book的地址
    }
    
    func main() {
        /*
            结构体嵌套:一个结构体中的字段,是另一个结构体类型。
                has a
        */
    
        b1 := Book{}
        b1.bookName = "西游记"
        b1.price = 45.8
    
        s1 := Student{}
        s1.name = "王二狗"
        s1.age = 18
        s1.book = b1    // 值传递
        fmt.Println(b1) // {西游记 45.8}
        fmt.Println(s1) // {王二狗 18 {西游记 45.8}}
        fmt.Printf("学生姓名:%s,学生年龄:%d,看的书是:《%s》,书的价格是:%.2f\n", s1.name, s1.age, s1.book.bookName, s1.book.price)
        // 学生姓名:王二狗,学生年龄:18,看的书是:《西游记》,书的价格是:45.80
    
        s1.book.bookName = "红楼梦"
        fmt.Println(s1) // {王二狗 18 {红楼梦 45.8}}
        fmt.Println(b1) // {西游记 45.8} 值传递,并未修改b1
    
        b4 := Book{bookName: "呼啸山庄", price: 76.9}
        s4 := Student2{name: "Ruby", age: 18, book: &b4}
        fmt.Println(b4)            // {呼啸山庄 76.9}
        fmt.Println(s4)            // {Ruby 18 0xc0000040a8}
        fmt.Println("\t", s4.book) // &{呼啸山庄 76.9}
    
        s4.book.bookName = "雾都孤儿"
        fmt.Println(b4)            // {雾都孤儿 76.9} 引用传递,修改了b4
        fmt.Println(s4)            // {Ruby 18 0xc0000040a8}
        fmt.Println("\t", s4.book) // &{雾都孤儿 76.9}
    
        s2 := Student{name: "李小花", age: 19, book: Book{bookName: "Go语言是怎样炼成的", price: 89.7}}
        fmt.Println(s2.name, s2.age)                       // 李小花 19
        fmt.Println("\t", s2.book.bookName, s2.book.price) // Go语言是怎样炼成的 89.7
    
        s3 := Student{
            name: "Jerry",
            age:  17,
            book: Book{
                bookName: "十万个为啥",
                price:    55.9,
            },
        }
        fmt.Println(s3.name, s3.age)                       // Jerry 17
        fmt.Println("\t", s3.book.bookName, s3.book.price) // 十万个为啥 55.9
    }
  • 相关阅读:
    希腊字母写法
    The ASP.NET MVC request processing line
    lambda aggregation
    UVA 10763 Foreign Exchange
    UVA 10624 Super Number
    UVA 10041 Vito's Family
    UVA 10340 All in All
    UVA 10026 Shoemaker's Problem
    HDU 3683 Gomoku
    UVA 11210 Chinese Mahjong
  • 原文地址:https://www.cnblogs.com/luwei0915/p/15630217.html
Copyright © 2011-2022 走看看