[13th][Day12] struct

Day8

go 的变数有着各式各样的型态: int float string pointer ...
那麽 ...当变数变成一大包的组合时,会发生什麽事呢 ...

一件衣服的 价格、size
车子的 年份、车门数、加速度、油耗、cc数
平面座标系中的 X,Y 座标
一栋房子的 坪数、面宽、楼高、建材...等等
若用单层的变数会显得非常的笨重

price := 1000000000
size := 100.17
width := 6.6
height := 3.6
kitchen := "BOSCH"
bathroom := "KOHLER"

变数的组合 struct
目前为止的例子中,变数都是储存单一的值。如果想用变数表示较复杂的概念,请使用 struct

golang 中会使用 结构 (struct) 来表示复合的概念;

来看个简单的例子

type Demo struct {
    x float64
    y float64
}

如果我们只需要使用结构,但不想创造新的型别,也可以使用匿名结构。

package main
 
import (
    "fmt"
)
 
func main() {
    p := struct {
        x float64
        y float64
    }{x: 3.0, y: 4.0}
 
    fmt.Println(p.x)
    fmt.Println(p.y)
}

可以分别印出 p struct 下,p.x p.y 的值

在宣告 struct时 同时 定义新的型别,以利後续程序呼叫,比方说环境变数、http client 的 domain、grpc client 的连线初始化

struct 是一整包变数的组合,那麽 …
当 struct 里面又包 struct 时
当 struct 里面包 struct 然後又包 struct 时 ... 会发生什麽事呢?

下面宣告了 Point 型别,该型别有两个属性 (field),分别是 x 和 y,两者资料型态皆为 float64

接着,我们宣告一个变数 p 以及及赋值;最後,我们呼叫 p 的属性 x 和 y。

func main() {
    p := Point{x: 3.0, y: 4.0}
 
    fmt.Println(p.x)
    fmt.Println(p.y)
}

struct 里的属性,不一定要相同

type Demo struct {
    x1 float64
    x2 int64
    x3 string
    x4 bool
    x5 map[string]interface{}
    x6 []int
}

struct 的属性,也可以用另一个 struct

package main

import "fmt"

type KitchenSet struct {
	Stove         string // 炉子 sove
	Oven          string // 烤炉
	Dishwasher    string // 洗碗机
	KitchenIsland string // 中岛
	Bar           string // 吧台
}

type House struct {
	Name    string
	Price   int
	Size    float64
	Kitchen KitchenSet
}

func main() {
	c := House{
		Name:  "Dibao",
		Price: 1000000000,
		Size:  200.87,
		Kitchen: KitchenSet{
			Stove:         "BOCSH",
			KitchenIsland: "Mediterranean",
			Oven:          "Taya",
		},
	}

	fmt.Println(c.Name)
	fmt.Println(c.Price)
	fmt.Println(c.Kitchen.Stove)

}

我宣告了一个 KitchenSet 类别
接着, House,类别,该型别有四个属性,分别是 Name、 Price、Size、Kitchen
其中 Kitchen 用到先前宣告的 KitchenSet 类别。

关於 struct 的部分在实务上是非常常用的,除非是很单纯的功能 的 func,不然...动辄十几二十几个参数,如果不用 struct 的方式做传递 , 方法或类别的命名会非常非常的杂乱


<<:  ViewModel 的 Single source of truth

>>:  Day10: Detection on AWS

【Day22】:旋转编码器—Encoder

Encoder Encoder也就是编码器,可用於将马达的旋转资讯转换为方波的形式输出,他的构造与原...

How do I eliminate QuickBooks Won't Export to Excel?

We are one of the top-rated, reliable, and self-go...

【第四天 - Queue 介绍】

Q1. Queue是什麽? 与 Stack 一样,是一种资料结构的概念,假设有一个容器是装马克杯的盒...

乙太网路光纤通道标准(FCoE)

-FCoE 融合网络适配器(来源:维基百科) 乙太网路光纤通道标准 (FCoE) 乙太网路光纤通道...

Z Ringtones - An intriguing assortment of telephone ringtones

In the event that you don't know which tune to pic...