• 71_Go基础_1_38 结构体是指类型


     1 package main
     2 
     3 import "fmt"
     4 
     5 type Person struct {
     6     name    string
     7     age     int
     8     sex     string
     9     address string
    10 }
    11 
    12 func main() {
    13     /*
    14         数据类型:
    15             值类型:int,float,bool,string,array,struct
    16 
    17             引用类型:slice,map,function,pointer
    18 
    19 
    20         通过指针:
    21             new(),不是nil,空指针
    22                 指向了新分配的类型的内存空间,里面存储的零值。
    23     */
    24 
    25     // 1.结构体是值类型
    26     p1 := Person{"王二狗", 30, "", "北京市"}
    27     fmt.Println(p1)
    28     fmt.Printf("%p,%T\n", &p1, p1) // 0xc0000d6000,main.Person
    29 
    30     p2 := p1
    31     fmt.Println(p2)
    32     fmt.Printf("%p,%T\n", &p2, p2) // 0xc0000d60c0,main.Person
    33 
    34     p2.name = "李小花"
    35     fmt.Println(p2) // {李小花 30 男 北京市}
    36     fmt.Println(p1) // {王二狗 30 男 北京市}
    37 
    38     // 2.定义结构体指针
    39     var pp1 *Person
    40     pp1 = &p1
    41     fmt.Println(pp1)                // &{王二狗 30 男 北京市}
    42     fmt.Printf("%p,%T\n", pp1, pp1) // 0xc0000d6000,*main.Person
    43     fmt.Println(*pp1)               // {王二狗 30 男 北京市}
    44 
    45     //(*pp1).name = "李四"
    46     pp1.name = "王五"
    47     fmt.Println(pp1) // &{王五 30 男 北京市}
    48     fmt.Println(p1)  // {王五 30 男 北京市}
    49 
    50     // 使用内置函数new(),go语言中专门用于创建某种类型的指针的函数
    51     pp2 := new(Person)
    52     fmt.Printf("%T\n", pp2) // *main.Person
    53     fmt.Println(pp2)        // &{ 0  }
    54     //(*pp2).name
    55     pp2.name = "Jerry"
    56     pp2.age = 20
    57     pp2.sex = ""
    58     pp2.address = "上海市"
    59     fmt.Println(pp2) // &{Jerry 20 男 上海市}
    60 
    61     pp3 := new(int)
    62     fmt.Println(pp3)  // 0xc0000aa0a0
    63     fmt.Println(*pp3) // 0
    64 }
  • 相关阅读:
    react脚手架搭建及配置
    mac使用技巧
    nginx配置
    vue常见前端UI库
    自定义指令
    代码缩进修改
    webpack学习入门
    webpack使用extract-text-webpack-plugin打包时提示错误
    webpack未成功全局安装
    基于jQuery的AJAX实现三级联动菜单
  • 原文地址:https://www.cnblogs.com/luwei0915/p/15630175.html
Copyright © 2020-2023  润新知