go语言从例子开始之Example18.struct结构体

寵の児 提交于 2019-12-02 04:49:46

Go 的结构体 是各个字段字段的类型的集合。这在组织数据时非常有用

Example:

package main

import "fmt"


type product struct{
    name string
    number int
}


func main(){
    //不指定字段。结构体赋值
    fmt.Println(product{"phone", 10})
    //注意字段名不加引号
    fmt.Println(product{name:"abc", number: 30})

    //省略字段默认为0
    fmt.Println(product{name: "def"})

    //使用点访问结构体属性。
    s := product{name: "yhleng", number: 30}
    fmt.Println(s.name, s.number)
    
    //&生成结构体指针,指针被自动解析引用
    sptr := &s
    fmt.Println(sptr.name)

    sptr.name = "xzdylyh"
    fmt.Println(sptr.name)
}

Result:

$ go run example.go
{phone 10}
{abc 30}
{def 0}
yhleng 30
yhleng
xzdylyh

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!