首页 > 其他分享 >0091-Go-结构体

0091-Go-结构体

时间:2022-10-30 08:34:24浏览次数:91  
标签:Println name age person Go main fmt 0091 结构

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/structs

目标

使用 Go 语言的结构体。

直接使用结构体

package main

import "fmt"

type person struct {
    name string
    age  int
}

func main() {

    fmt.Println(person{"Bob", 20})

    fmt.Println(person{name: "Alice", age: 30})

    fmt.Println(person{name: "Fred"})
    // 取地址
    fmt.Println(&person{name: "Ann", age: 40})
}

局部变量指针

package main

import "fmt"

type person struct {
    name string
    age  int
}

func newPerson(name string) *person {

    p := person{name: name}
    p.age = 42
    return &p
}

func main() {

    fmt.Println(newPerson("Jon"))
}

获取和修改

package main

import "fmt"

type person struct {
    name string
    age  int
}

func main() {

    s := person{name: "Sean", age: 50}
    fmt.Println(s.name)

    sp := &s
    fmt.Println(sp.age)

    sp.age = 51
    fmt.Println(sp.age)
}

总结

使用 Go 语言的结构体。

附录

标签:Println,name,age,person,Go,main,fmt,0091,结构
From: https://www.cnblogs.com/jiangbo4444/p/16840461.html

相关文章

  • 0092-Go-方法
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/methods目标使用Go语言的方法。值方法packagemainimport"fmt"typerectstruct{......
  • 0093-Go-接口
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/interfaces目标使用Go语言的接口。定义接口typegeometryinterface{area()float64......
  • 0094-Go-结构体嵌入
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/struct-embedding目标使用Go语言的结构体嵌入。定义结构体typebasestruct{numint......
  • 0095-Go-泛型
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/generics目标使用Go语言的泛型。泛型函数packagemainimport"fmt"funcMapKeys[Kcom......
  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......
  • 0076-Go-常量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/constants目标使用Go语言的常量。示例packagemainimport("fmt""math")co......
  • 0077-Go-for 循环
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/for目标使用Go语言的for循环。单条件循环类似其它语言中的while循环。packagemain......
  • 0078-Go-if else 条件判断
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/if-else目标使用Go语言的if/else条件判断。条件判断条件判断的小括号可以省略,但是后面的......
  • 0079-Go-switch 分支
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/switch目标使用Go语言的switch分支语句。整数分支packagemainimport"fmt"funcmai......
  • 0080-Go-数组
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/arrays目标使用Go语言的数组。申明数组packagemainimport"fmt"funcmain(){v......