Go 结构体

 1.

package main

import "fmt"

type Books struct {
    title   string
    author  string
    subject string
    book_id int
}

func main() {

    // 创建一个新的结构体
    fmt.Println(Books{"Go 语言", "www.runoob.com", "Go 语言教程", 6495407})

    // 也可以使用 key => value 格式
    fmt.Println(Books{title: "Go 语言", author: "www.runoob.com", subject: "Go 语言教程", book_id: 6495407})

    // 忽略的字段为 0 或 空
    fmt.Println(Books{title: "Go 语言", author: "www.runoob.com"})
}

输出

{Go 语言 www.runoob.com Go 语言教程 6495407}
{Go 语言 www.runoob.com Go 语言教程 6495407}
{Go 语言 www.runoob.com  0}

2.

package main

import "fmt"

type Books struct {
    title   string
    author  string
    subject string
    book_id int
}

func main() {
    var Book1 Books /* 声明 Book1 为 Books 类型 */
    var Book2 Books /* 声明 Book2 为 Books 类型 */

    /* book 1 描述 */
    Book1.title = "Go 语言"
    Book1.author = "www.runoob.com"
    Book1.subject = "Go 语言教程"
    Book1.book_id = 6495407

    /* book 2 描述 */
    Book2.title = "Python 教程"
    Book2.author = "www.runoob.com"
    Book2.subject = "Python 语言教程"
    Book2.book_id = 6495700

    /* 打印 Book1 信息 */
    fmt.Printf("Book 1 title : %s
", Book1.title)
    fmt.Printf("Book 1 author : %s
", Book1.author)
    fmt.Printf("Book 1 subject : %s
", Book1.subject)
    fmt.Printf("Book 1 book_id : %d
", Book1.book_id)

    /* 打印 Book2 信息 */
    fmt.Printf("Book 2 title : %s
", Book2.title)
    fmt.Printf("Book 2 author : %s
", Book2.author)
    fmt.Printf("Book 2 subject : %s
", Book2.subject)
    fmt.Printf("Book 2 book_id : %d
", Book2.book_id)
}

输出

Book 1 title : Go 语言
Book 1 author : www.runoob.com
Book 1 subject : Go 语言教程
Book 1 book_id : 6495407
Book 2 title : Python 教程
Book 2 author : www.runoob.com
Book 2 subject : Python 语言教程
Book 2 book_id : 6495700

原文地址:https://www.cnblogs.com/sea-stream/p/10333255.html